It is important to ensure that validation is triggered within the submit event for accurate results.
Currently, the validation only occurs when the form is loaded, not when it is filled and submitted.
Avoid using Array from unnecessarily.
It's worth noting that your test was only checking for the existence of a single character from a-zA-Z.
(() => {
'use strict'
document.querySelectorAll('.needs-validation')
.forEach(form => {
form.addEventListener('submit', event => {
const nameinp = document.getElementById('nameinp');
let isPasswordValid = false;
let en = nameinp.value.trim();
const ptern = /^[A-Za-z]*$/;
isPasswordValid = ptern.test(en);
console.log( isPasswordValid)
if (!form.checkValidity() || !isPasswordValid) {
event.preventDefault()
event.stopPropagation()
console.log('not valid')
}
// else // I would expect an else here
form.classList.add('was-validated')
}, false)
})
})()
<form id="Oform" action="" class="form-control needs-validation" novalidate>
<label for=" OName">name</label>
<input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
<div class="input-group form-control">
<label class="col-sm-12" for="IPrange"> family</label>
<input required class="form-control" type="number" max="254" min="1" name="" id="IPrange">
</div>
<button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>
And if there is only one form then even less reason
(() => {
'use strict'
document.querySelector('.needs-validation')
.addEventListener('submit', event => {
const form = event.target;
form.classList.remove('was-validated')
form.classList.remove('invalid')
const nameinp = document.getElementById('nameinp');
let isPasswordValid = false;
let en = nameinp.value.trim();
const ptern = /^[A-Za-z]*$/;
isPasswordValid = ptern.test(en);
if (!form.checkValidity() || !isPasswordValid) {
event.preventDefault()
event.stopPropagation()
form.classList.add('invalid')
}
else {
form.classList.add('was-validated')
}
})
})()
.invalid { border: 1px solid red; }
.was-validated { border: 1px solid green; }
<form id="Oform" action="" class="form-control needs-validation" novalidate>
<label for=" OName">name</label>
<input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
<div class="input-group form-control">
<label class="col-sm-12" for="IPrange"> family</label>
<input required class="form-control" type="number" max="254" min="1" name="" id="IPrange">
</div>
<button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>