Why doesn't using the search method to find a . work the way I expect in JavaScript? -
in js code, i'm trying validate email address.
var validateemail = function () { var email = $("email").value; var symbol = email.search("@"); var domain = email.substring(email.indexof('@')).substr(1); var validdomain = domain.search("."); if (symbol == -1) { alert(email + " not valid email address."); } else if (validdomain == -1) { alert(email + "is not valid domain name."); } else { alert(email + " valid email address."); } };
i'm sure there better way validate email address, way i'm doing practice js properties , methods. learning simple basic stuff. not sure if example consider best practice.
the problem:
var validdomain = domain.search(".");
is not pulling period string. can point out problem i'm having here.
here's jsfiddle: http://jsfiddle.net/udv7q/
the main problem search
expects regular expression passed. if argument isn't one, it's implicitly converted one. .
special character in regular expressions, you'd need escape (you might use regex literal).
var validdomain = domain.search(/\./);
demo: http://jsfiddle.net/h4hx5/
note simple validation doesn't ensure input valid email. there's specification defines valid email is, , it's quite bit more complex this. if works you, that's great; it's hard validate email :)
reference:
Comments
Post a Comment