简体   繁体   English

在第二次单击按钮时验证不起作用

[英]Validation is not working in second time button click

I am adding username and email to the userlist and validating email when adding. 我正在将用户名和电子邮件添加到用户列表,并在添加时验证电子邮件。 Validation is working when the page loads for the first time, If I tried to enter invalid email for second time and click the add button it is not working.. 首次加载页面时,验证工作正常。如果我第二次尝试输入无效的电子邮件,然后单击“添加”按钮,则该验证不起作用。

<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>

<script type="text/javascript">
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-Z0-9-.]+$/;
        if (reg.test(email.value) == true) {
            entry.appendChild(document.createTextNode(username + ' ' + email.value));
            list.appendChild(entry);
            return false;
        }
        else {
            email.className += 'errorclass';
            return false;                             
        }
    }
    else{
        alert("Please Enter Email Id");
        return false;
    }
}
</script>
<style>
.errorclass{
    border:1px red solid;
}
</style>

Each time there is a validation error you add 'errorclass' to the email class. 每次出现验证错误时,您都将“ errorclass”添加到电子邮件类别。 So the second time is "errorclasserrorclass" that is not defined in the css. 因此第二次是在CSS中未定义的“ errorclasserrorclass”。

Use: 采用:

email.setAttribute('class','errorclass')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM