I am trying to learn JavaScript… I have function like, I take the format user id field… which is an email address and try to check if it matches below condition. However even thought I give the user name >3 and domain as gmail.com, I still get false return…Can someone please check and let me know why it is going into the if loop, do I have to trim the text or something.
Also if you can tell me how to write this effectively using jQuery that would help me learn. But if you think I am mixing two thing here… My priority is first question above.
function isValidate(eltt) {
var flag = true;
var upos = eltt.indexOf("@");
var uendpos = eltt.indexOf(".com");
var totlength = eltt.length;
var domain = eltt.slice(upos,totlength);
if ( upos < 3 | domain!="gmail.com" | uendpos=== -1) {
flag=false;
}
return flag;
}
First, the problem is that you’re using
|instead of||. (The|is a bitwise or, which in this case will yield a basically random result by combining the bits of the binary representation of your conditions. Chances are, you’ll never need|; so use||and forget that|even does anything by itself.)Second, this validation would be easier with a regular expression:
That is, it must start with (
^) at least three characters.{3,}, followed by the literal text@gmail.com, with nothing after it ($).