电子邮件验证功能运行不正常

时间:2015-01-28 06:01:34

标签: javascript regex email

我有一个注册表单,其中包含电子邮件字段。我做了一个正则表达式来验证它,并且正则表达式工作正常。我面临的问题是,完成这项工作的功能是不起作用的。这将从以下内容变得更加清晰:

var email = getEle('email', clas)[0].value; // 'getEle()' is a function which returns an element whose calss is the first arguement
console.log(email); // logs correct thing which means that email has been caught by the javascript       
function em(){ // this function will check email
        var eln = email.match(/([A-Za-z0-9\._\-]+)@([A-Za-z]+).([A-Za-z]+)/);
        console.log(eln);   
            if(eln.length ===4){
                email = email;
            }else{
                Error = Error + "2) Your Email address is not valid. Please enter valid email Address\n"
            }
    };em();// end

我的电子邮件验证regex工作正常,您可以在此处看到regex101.com
给我的错误是:Uncaught TypeError: Cannot read property 'length' of null
第一个日志记录正确但第二个日志记录null
如果这是在控制台中完成的(我使用谷歌浏览器),则不会给出任何错误。

问题是,如果手动完成此事情时没有给出错误,那么在将其作为功能代码写入时,为什么会出现错误。

错误是什么。

完整代码:

var getEle = function(ele, type){
    if(type ==="id"){
    return document.getElementById(ele);
    };
    if(type==="class"){
        return document.getElementsByClassName(ele);
    };
    if(type === 'tag'){
        return docuemnt.getElementsByTagName(ele);
    };
};
function signUpform(){
    var fname = getEle('fname', clas)[0].value,
        lname = getEle('lname', clas)[0].value,
        email = getEle('email', clas)[0].value,
        phoneNo = getEle('phoneNo', clas)[0].value,
        age = getEle('age', clas)[0].value,
        date = getEle('date', clas)[0].value,
        username = getEle('username', clas)[0].value,
        password = getEle('password', clas)[0].value,
        re_pass = getEle('re_pass', clas)[0].value,
        Error = "Errors List: \n";
    console.log(email);
    function flname(){ // this function will check the first name and the last name 
        if(fname === "" || lname ===""){
            Error = Error +'1) You cannot leave first name and last name blank\n';
        }else{
            fname.value = fname.value.replace(/[0-9]+/g,"");
            lname = lname.replace(/[0-9]+/g,"");
        };
    };flname();// end

    function em(){ // this function will check email
        var eln = email.match(/([A-Za-z0-9\._\-]+)@([A-Za-z]+).([A-Za-z]+)/);
        console.log(eln);   
            if(eln.length ===4){
                email = email;
            }else{
                Error = Error + "2) Your Email address is not valid. Please enter valid email Address\n"
            }
    };em();// end 

};

1 个答案:

答案 0 :(得分:1)

无需检查匹配数组的长度,只需简化em函数,如下所示:

function em(){ // this function will check email
    var eln = /\b[\w.-]+@[A-Za-z]+\.[A-Za-z]+\b/.test( email );
    if (!eln)
       Error = Error + "2) Your Email address is not valid. Please enter valid email";
};