I have a form that validates and is working as expected but the form still submits even though it is prompting a validation error. Tried various different things but can’t seem to make it stop submitting the form with incorrect validation.
function Validate() {
const name = document.forms.ValidateForm.name.value;
console.log(name);
if (name === "" ||
name.includes('0') || name.includes('1') ||
name.includes('2') || name.includes('3') ||
name.includes('4') || name.includes('5') ||
name.includes('6') || name.includes('7') ||
name.includes('8') || name.includes('9')) {
window.alert("Office Name cannot be Empty");
name.focus();
return false;
}
if (name.length < 3) {
alert("Office Name must be more than 3 characters");
name.focus();
return false;
}
return true;
}
<form action="#" method="post" enctype="multipart/form-data" name="ValidateForm" onsubmit="return Validate();" id="ValidateForm">
<input type="text" name="name" id="name">
<input type="submit" value="Add Office">
</form>
3
Answers
The issue in your code is because you’re calling the
focus()
method on the string returned from theinput
element, not theinput
itself. This is causing an error to be thrown which means thatreturn false
is never hit.That being said, and as @mykaf mentioned in the comments, this issue, along with the quality of your code, can be improved by removing the inline
onclick
attribute and binding your event handler in JS.Also note the use of a regular expression to check for an integer in the entered ‘name’ string.
Maybe you need to use preventDefault().
Use
Event::preventDefault()
to halt the form’s submission. Also callfocus()
on the input, not its value.You can use
try/catch
to avoid code duplication.Also your error messages could be more descriptive: