Why is my Javascript form validation not working properly? -
why validation failing on second attempt here? on first attempt validation works fine, on second run, accept inappropriate values in email field. first 2 fields work fine, third field accept text after first run. validates if change value in email field, otherwise keep displaying error , failing validate should.
function validate(){ clearerrors(); var errorflag = true; var name = document.getelementbyid("name"); nameval = name.value; if(nameval.length === 0){ var nameerror = document.getelementbyid("nameerror"); nameerror.style.display = "block"; errorflag = false; } var phone = document.getelementbyid("phone") var phoneval = phone.value; if(isnan(phoneval) || (phoneval < 1000000000 || phoneval >10000000000)){ errorflag = false; var phoneerror = document.getelementbyid("phoneerror"); phoneerror.style.display = "block"; } var email = document.getelementbyid("email"); var emailval = email.value; var restr = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"; if((restr.match(emailval))){ errorflag = false; var emailerror = document.getelementbyid("emailerror"); emailerror.style.display = "block"; } return errorflag; } function clearerrors(){ var nameerror = document.getelementbyid("nameerror"); nameerror.style.display = "none"; var phoneerror = document.getelementbyid("phoneerror"); phoneerror.style.display = "none"; var emailerror = document.getelementbyid("emailerror"); emailerror.style.display = "none"; }
your validator fail on email, because feeding string .match
, when needs regex.
you have call .match
on email itself, regex argument.
you need negate return value check if not match, or use .test
.
this bit:
var restr = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"; if((restr.match(emailval))){
should replaced with:
var re = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i; if(!emailval.match(re)){
of if can't use regex literal reason:
var re = new regexp("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$", "i"); if(!emailval.match(re)){
or using .test
instead of .match
:
var re = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i; if(!re.test(emailval)){
note i
case-insensitive matching, emails don't have entered in all-caps.
Comments
Post a Comment