开发者

JavaScript email validation not working correctly, HELP? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is the best regular expression for validating email addresses?

Hi All,

I have this regex/code to validate a email address:

var testEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

if ( testEmail.test(oForm["email"]) == false){
    chErrorMessage += "\nValid email address";
    bSubmit = false;
}

The code doesn't seem to be doing the test co开发者_开发知识库rrectly, whether the email is formatted correctly or not.

I'm a beginner at JavaScript. Any help would be greatly appreciated, Thanks


I use the jQuery Validation Plugin for this: http://docs.jquery.com/Plugins/validation

It supports email address validation.


Firstly, I'd get the input object of the form this way

document.oForm["email"]

instead of

oForm["email"]

Then, you should get the value of the input, not the input itself:

document.oForm["email"].value

Also, you want to execute the conditional code if the result is true, not false, so the condition should be:

testEmail.test(document.oForm["email"].value) == true

But it is not very elegant to compare a boolean value to true or false, since the compared value itself is enough to be used as the condition:

if (testEmail.test(document.oForm["email"].value)) {
    // ...
}

Your code worked for me after these changes. However, I would use the solution with JQuery because it would take care of all the infinite details your regex ignores about e-mails. OTOH, I hope you got a better understanding of how regexes work in JavaScript anyway.

HTH


Try this code out:-

/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function echeck(str) {

        var at="@"
        var dot="."
        var lat=str.indexOf(at)
        var lstr=str.length
        var ldot=str.indexOf(dot)
        if (str.indexOf(at)==-1){
           return false
        }

        if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
           return false
        }

        if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
            return false
        }

         if (str.indexOf(at,(lat+1))!=-1){
            return false
         }

         if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
            return false
         }

         if (str.indexOf(dot,(lat+2))==-1){
            return false
         }

         if (str.indexOf(" ")!=-1){
            return false
         }

         return true                    
    }

function ValidateForm(){
    return echeck(document.oForm["email"].value);
 }

And finally just call ValidateForm() and whatever return value you get that is the validity of the email!

Cheers! :D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜