I’m doing form validation, when i call my function ‘validtae( )’ using ‘onsbmit’ in form it doesn’t work. when i click button submit the validation that suppose to happen doesn’t work i have no idea why it’s not working, i tried add return in onsubmit still not working. i tried calling the function with onfocus inside input tag and it works but i want to work when i click the button.
// getting inputs
const namee = document.forms['myForm']['name'];
const email = document.forms['myForm']['email'];
const password =document.forms['myForm']['password'];
// getting where the erroe gonna show
const nameerror = document.querySelector('#nameerror');
const emailerror = document.querySelector('#emailerror');
const passworderror = document.querySelector('#passworderror');
// validation function
function validate(){
if(namee.value == "" ){
namee.style.border = "2px solid red";
nameerror.textContent ="name cannot be blank";
namee.focus();
return false;
}
if(email.value == "" ){
email.style.border = "2px solid red";
emailerror.textContent ="email cannot be blank";
email.focus();
return false;
}
if(password.value == "" ){
password.style.border = "2px solid red";
passworderror.textContent ="password cannot be blank";
password.focus();
return false;
}
}
<form name="myForm" method="post" onsubmit="return validate()">
<input type="text" id="name" name="name" placeholder="Name" required>
<div id="nameerror"></div>
<input type="email" id="email" name="email" placeholder="Email" required>
<div id="emailerror"></div>
<input type="password" id="password" name="password" placeholder="Create a password"
required>
<button id="submit" type="submit">Sign Up</button>
</form>
Please try
It should work.
If any of the validation checks failed you should use
event.preventDefault()
Check this out
change the submit button to input, it will work
e.g:
input type=”submit” value=”submit”
I assume you are wondering why the error message isn’t shown. That’s likely because the browser’s own validation for the
required
attribute kicks in beforeonsubmit
is called. I.e.validate
isn’t even called at the moment, which you can easily verify by adding aconsole.log
call.If that’s not what you want then remove the
required
attributes.Alternatively just let the browser handle the validation and remove your own
validate
function.