1

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;
}
4

1 回答 1

1

首先,问题是您使用|的是||. (这|是一个按位或,在这种情况下,它将通过组合条件的二进制表示的位来产生一个基本随机的结果。很有可能,你永远不需要|;所以使用||并忘记它|甚至可以自己做任何事情。)

其次,使用正则表达式进行验证会更容易:

if (!eltt.match(/^.{3,}@gmail\.com$/)) {
  return false;
}

也就是说,它必须以 ( ^) 开头,至少三个字符.{3,},然后是文字文本@gmail.com,后面没有任何内容 ( $)。

于 2012-07-01T01:33:15.503 回答