使用jscript验证电子邮件地址而不使用正则表达式

时间:2013-12-14 20:41:58

标签: javascript validation email jscript

我们可以通过实施以下三条规则,使用JavaScript对电子邮件地址进行非常基本的验证:

1.电子邮件地址必须为@ character

2.电子邮件地址必须有。(点)字符

3. @和。(点)

之间必须至少有2个字符

5 个答案:

答案 0 :(得分:1)

这满足了您所说的所有规则,并且不允许@启动地址而不允许。结束地址。它不占多个。在地址。

function testEmailAddress(emailToTest) {
    // check for @
    var atSymbol = emailToTest.indexOf("@");
    if(atSymbol < 1) return false;

    var dot = emailToTest.indexOf(".");
    if(dot <= atSymbol + 2) return false;

    // check that the dot is not at the end
    if (dot === emailToTest.length - 1) return false;

    return true;
}

Fiddle

答案 1 :(得分:0)

你能试试吗,

 var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

if (!filter.test(email.value)) {
      alert('Please provide a valid email address');

答案 2 :(得分:0)

``这是有效的......我自己的创作:)Email Validation

<input type=”text” name=”email” id=”email”  />
<input type=”button” name=”btnok” onclick=”validate()” />

Javascript功能

   <script type=”text/javascript”>
function validate()
{
var str;
var t=1;
str =document.getElementById(‘email’).value;
if(document.getElementById(‘email’).value==”")
{
alert(“Empty”);

}
var res = str.split(‘@’);
if(str.split(‘@’).length!=2)
{
alert(“zero @ OR morethan one @ “);
t=0;
}
var part1=res[0];
var part2=res[1];

// part1
if(part1.length==0)
{
alert(“no content bfr @”);
t=0;
}
if(part1.split(” “).length>2)
{
alert(“Invalid:Space before @”)
t=0;
}

//chk afr @ content:  part2
var dotsplt=part2.split(‘.’);  //alert(“After @ :”+part2);
if(part2.split(“.”).length<2)
{
alert(“dot missing”);
t=0;
}
if(dotsplt[0].length==0 )
{
alert(“no content b/w @ and dot”);
t=0;
}
if(dotsplt[1].length<2 ||dotsplt[1].length>4)
{alert(“err aftr dot”);
t=0;
}

if(t==1)
alert(“woooooooooooooooooooowwwww…it is a valid email”);

}

</script>

答案 3 :(得分:0)

var john = {
  name : 'Sky',
  age : 23, 
  calculateBirthYear : () => console.log("My name is " + this.name)
}
john.calculateBirthYear();

答案 4 :(得分:-2)

var checkEmail = function(value) {

    var valid = true;

    if (value.indexOf('@') == -1) {
        valid = false;
    } else {

        var parts = value.split('@');
        var domain = parts[1];

        if (domain.indexOf('.') == -1) {

            valid = false;

        } else {

            var domainParts = domain.split('.');
            var ext = domainParts[1];

            if (ext.length > 4 || ext.length < 2) {

                valid = false;
            }
        }

    }


    return valid;

};

var form = document.getElementById('test');

var validate = function(event) {
    event.preventDefault();
    var val = document.getElementById('email').value;
    var valid = checkEmail(val);

    if (!valid) {

        alert('Not a valid e-mail address');
    } else {

        alert('Valid e-mail address');

    }
};

form.addEventListener('submit', validate, false);

有许多验证电子邮件地址的技巧,每种验证方法都有自己的优缺点。上述方法不需要理解正则表达式