I was trying to use the regex /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.){1,2}[a-zA-Z]{2,}))$/
in my javascript code to validate email input. But the function is not returning true even if the email id is valid. Does anyone help me to understand what’s wrong here? The regex which I am using here is matching the email id. But when I use it in the function it’s not working.
The following is my code
var emailInput = $('[data-val-type=email]');
var submitButton = $('.button.submit-button');
submitButton.attr('disabled', true);
emailInput.keyup(function() {
var mailid = emailInput.val();
var filter = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.){1,2}[a-zA-Z]{2,}))$/;
if (!filter.test(mailid.toLowerCase())) {
console.log("Email invalid: " + mailid);
emailInput.focus();
} else {
console.log("Email valid: " + mailid);
}
});
Reproducible example is here JSFiddle
2
Answers
Your code seems to work fine for me. I have copy/pasted it here but made a few small changes:
keyup
eventi
flag instead of usingemailInput.val().toLowerCase()
.on('keyup'
instead of.keyup(
isValid
variable to make things easier to understand inside the event codekeyup
event is now triggered upon first load instead of just disabling the button on first loadWhy don’t you simply use form validation with required attribute ?