简体   繁体   中英

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. So the second time is "errorclasserrorclass" that is not defined in the css.

Use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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