I’m trying to use a regular expression validation using .match for email validation and for some reason it only shows invalid even though all formats are followed!
javascript function
function check_email_valid(emails) {
var emailRegex = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$';
if (emails.match(emailRegex)) {
jQuery('#<%=Label16.ClientID%>').css('color', 'green');
jQuery('#<%=Label16.ClientID%>').show();
jQuery('#<%=Label16.ClientID%>').text("Valid Email!");
}
else {
jQuery('#<%=Label16.ClientID%>').css('color', 'red');
jQuery('#<%=Label16.ClientID%>').show();
jQuery('#<%=Label16.ClientID%>').text("Invalid Email!");
}
Event trigger
$('#<%=TextBox8.ClientID%>').keyup(function () {
var email = jQuery('#<%=TextBox8.ClientID%>').val();
check_email_valid(email);
});
I keyed in test@mail.com and got “Invalid Email!”. Any idea why?
JavaScript has a slightly different way of defining regex patterns than other languages. They’re not strings, but instead simply start with a slash, end with one, and after that you can specify some flags.
Your pattern is defined like this:
The i flag at the end of the pattern makes it case insensitive.