[英]Chars in Javascripts function returing false even though charcters do not satisify if condition
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. 我正在尝试学习JavaScript ...我有类似的功能,我采用格式用户ID字段...这是一个电子邮件地址,并尝试检查其是否符合以下条件。 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. 但是,即使以为我将用户名> 3和域都设置为gmail.com,我仍然会得到错误的返回...有人可以检查一下,让我知道为什么它会进入if循环,我是否必须修剪文本或的东西。
Also if you can tell me how to write this effectively using jQuery that would help me learn. 另外,如果您可以告诉我如何使用jQuery有效地编写代码,这将对我有所帮助。 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: 其次,使用正则表达式可以使验证更加容易:
if (!eltt.match(/^.{3,}@gmail\.com$/)) {
return false;
}
That is, it must start with ( ^
) at least three characters .{3,}
, followed by the literal text @gmail.com
, with nothing after it ( $
). 也就是说,它必须以( ^
)至少三个字符.{3,}
开头,后跟文字文本@gmail.com
,其后没有任何字符( $
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.