function validateText1() {
var txt = document.getElementById("Surname");
var a = txt.value.search(/^[a-zA-Z]{2,}$/);
if (a != 0) {
alert("Invalid Text.\n")
return false;
}
else return true;
}
I came across this validation form, but I don't understand why is it a!=0
, shouldn't it be a==0
, since a number, representing the position of the first occurrence of the specified search value, or -1
is if no match is found.
Technically the search function tries to find text in a string, and returns the index of the first occurrence of the string.
For example:
var txt = "This is a funny string";
var resultIndex = txt.search("funny");
// resultIndex will return 10
If it is not found, it will return -1.
It should really be if (a >= 0), but the above will work too.
It's a != 0
because it's testing for a failing search, which is when it reports "Invalid input" and returns false
. a == 0
would mean that the search found a match, and in that case the input is valid and it returns true
.
The search indicates it will return the index at which position the match starts, so if it doesn't start at 0 it means a special character is used.
Altho I would never use this to validate my forms. Matching names is pretty hard.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.