-1

I am validating the email by adding the user and email to the list, the pattern that I provided is not working for some patterns like xyz.xyz kkk.kk and my message is not displaying when it is validating Here is my code..

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;
}
Skwal
  • 2,160
  • 2
  • 20
  • 30
user3282116
  • 39
  • 1
  • 8
  • 1
    Relevant .. [SO post](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Stphane Apr 03 '14 at 14:22
  • Here's the official regex for email addresses: http://ex-parrot.com/pdw/Mail-RFC822-Address.html – Cydrick Trudel Apr 03 '14 at 14:23
  • Hi, try to be more precise when asking regex questions. What do you mean, 'not working'? It's matching where it shouldn't? The contrary? Does your message sometimes show up? Never? What do you want to validate (as in, give input and expected output)? And please do not to dump all your code in a block, keep only the relevant part. – Robin Apr 03 '14 at 14:28
  • when the page load my validation works and I tried again the validation is not working at all i think it is not regex pattern problem – user3282116 Apr 03 '14 at 14:31

1 Answers1

0

Replace

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

with

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

Refer JavaScript Regular Expression Email Validation

Community
  • 1
  • 1
Birlla
  • 1,700
  • 2
  • 15
  • 17