电子邮件验证模式不适用于某些测试模式

时间:2014-04-03 14:21:40

标签: javascript jquery regex

我通过将用户和电子邮件添加到列表来验证电子邮件,我提供的模式不适用于某些模式,如xyz.xyz kkk.kk,并且我的消息在验证时没有显示这是我的代码..

HTML

<form id="myform">
    <h2>Add a User:</h2>
    <input id="username" type="text" name="username" placeholder="name">
    <input id="email" type="text"  name="email" placeholder="email">
    <button onclick='return addUser();' type="submit">add user</button>
</form>

<h2>UsersList:</h2>
<ul id="users"></ul>

JS

function addUser(){
    var list = document.getElementById('users');
    var username =document.getElementById('username').value;
    var email = document.getElementById('email');
    var entry = document.createElement('li');
    if (email.value != '') 
    {
        reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test(email.value) == true) {
            entry.appendChild(document.createTextNode(username + ' ' + email.value));
            list.appendChild(entry);
            return false;
        }
        else {
            email.className += 'errorclass';
            email.innerHtml = "Please enter valid emailid";
            return false;                             

        }

CSS

.errorclass{
    border: 1px red solid;
}

1 个答案:

答案 0 :(得分:0)

替换

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

 reg = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

参考JavaScript Regular Expression Email Validation