为什么不使用搜索方法找到a。以JavaScript的方式工作?

时间:2021-11-20 13:19:14

In my js code, I'm trying to validate an email address.

在我的js代码中,我试图验证一个电子邮件地址。

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 + " is not a valid email address.");
    } else if (validDomain == -1) {
        alert(email + "is not a valid domain name.");
    } else {
        alert(email + " is a valid email address.");
    }

};

I'm sure there is a better way to validate an email address, but the way I'm doing it is to practice with js properties and methods. Learning simple basic stuff. Not even sure if this example is consider best practice.

我确信有更好的方法来验证电子邮件地址,但是我这样做的方法是使用js属性和方法。学习简单的基本的东西。甚至不确定这个例子是否被认为是最佳实践。

The problem:

存在的问题:

var validDomain = domain.search(".");

is not pulling the period from the string. Can someone point out the problem I'm having here.

不是从弦拉出周期。有人能指出我在这里遇到的问题吗?

Here's the jsfiddle: http://jsfiddle.net/UDv7q/

这是jsfiddle:http://jsfiddle.net/UDv7q/

1 个解决方案

#1


3  

The main problem is that search expects a regular expression be passed. If the argument isn't one, it's implicitly converted to one. . is a special character in regular expressions, so you'd need to escape it (you might as well use a regex literal).

主要的问题是搜索期望通过一个正则表达式。如果参数不是1,它就隐式转换为1。在正则表达式中是一个特殊的字符,因此您需要避免它(您可以使用regex文本)。

var validDomain = domain.search(/\./);

DEMO: http://jsfiddle.net/h4hx5/

演示:http://jsfiddle.net/h4hx5/

Note that this simple validation doesn't actually ensure the input is a valid email. There's a specification that defines what a valid email is, and it's quite a bit more complex than this. But if it works for you, that's great; it's usually hard to fully validate an email :)

注意,这个简单的验证实际上并不能确保输入是有效的电子邮件。有一个规范定义了一个有效的电子邮件是什么,而且它比这个复杂得多。但如果它对你有用,那就太好了;通常很难完全验证一封电子邮件:)

Reference:

参考:

#1


3  

The main problem is that search expects a regular expression be passed. If the argument isn't one, it's implicitly converted to one. . is a special character in regular expressions, so you'd need to escape it (you might as well use a regex literal).

主要的问题是搜索期望通过一个正则表达式。如果参数不是1,它就隐式转换为1。在正则表达式中是一个特殊的字符,因此您需要避免它(您可以使用regex文本)。

var validDomain = domain.search(/\./);

DEMO: http://jsfiddle.net/h4hx5/

演示:http://jsfiddle.net/h4hx5/

Note that this simple validation doesn't actually ensure the input is a valid email. There's a specification that defines what a valid email is, and it's quite a bit more complex than this. But if it works for you, that's great; it's usually hard to fully validate an email :)

注意,这个简单的验证实际上并不能确保输入是有效的电子邮件。有一个规范定义了一个有效的电子邮件是什么,而且它比这个复杂得多。但如果它对你有用,那就太好了;通常很难完全验证一封电子邮件:)

Reference:

参考: