I have name ( fname+lname) and email and i have their regexes but they are not validating
var fnlnregex = /^[\w\/\s\.-]+$/; //first name + last name
var usremailregex = /^[@.\w]+$/;
if(!usremailregex.test($("#Eml").val())){
flag = false;
$("#Eml").attr('class','red');
}else{
$("#Eml").attr('class','');
}开发者_运维问答
But it is not validating the email field it is taking the following data as correct //if i enter only "abc" in the email field it is not taking as wrong
fnlnregex - this should not allow numbers but in my same if for name regex it is allowing . How do i correct the two
/^[@.\w]+$/
means:
start of string - one or more of a combination of @, any character or word boundary - end of string
I must say that it's pretty useless. The .
means any character which includes @
and \w
already.
As for why abc
matches - well, it matches beginning - any character - end
.
What you're looking for is something along the lines of:
/^[a-z0-9]+@[a-z0-9]+\.[a-z]+$/i
which translates to:
beginning - one or more letters or digits - a @ - one or more letters or digits - a . - one or more letters - end
.
The i
means that it's case-insensitive.
your usremailreg will never work to validate emails. It accepts anything that has at least ONE character that's a .
, a @
, or a-z0-9A-Z
. so @@@@@@@@@
is perfectly valid.
Try this one on for size to validate RFC822-compliant addresses:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
usremailregex: if the string consists only of '@', '.', or word characters, allow it. That is valid for abc.
In the first regex you're using the \w shorthand, which matches any word character, including numbers; you could try with:
/^[A-Za-z\/\s\.-]+$/
if you just want alphabetical characters.
精彩评论