0

I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.

"email":{
        "regex":"/^([\.a-z0-9_\-]+[@][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
        "alertText":"* Invalid email address"}

What are the changes should me made here?

Niroshan
  • 19
  • 1
  • 5

4 Answers4

1

You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.

Since it's Javascript can you do something like:

if (str === '') {
  validations['email'] = {}
} else {
  validations['email'] = {
    // email validation
  }
}

I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.

user3254198
  • 763
  • 6
  • 23
  • you can simplify things up by just having one conditional statement.. `if (str) //do validations` it would only validate the email if str (*email input value*) returns a truthy values. – JF-Mechs Jul 15 '16 at 05:02
  • yea I was thinking of that but didn't bother changing it. It's pretty cool to default things like that with a initial value and clear it out later with a single operator. It's nice to do it that way, isn't it? :D – user3254198 Jul 15 '16 at 05:07
0

Try this

var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
    alert('Please enter a valid email address.');
    return false;
}
Tony Vincent
  • 13,354
  • 7
  • 49
  • 68
0

Try it :

if(email.length > 0) {
  //Test Email is Valid Or Not 
}

Final code :

<html>
    <head>
    </head>
    <body>
        Enter Email : <input type="text" id="txt">
        <button onclick="isValid()">Test</button>
        <script>
           var ele = document.getElementById("txt");
            function isValid(){
                var email = ele.value;
                var patt = /^[a-zA-Z0-9_\-]+@[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
                if(email.length > 0) {
                    if(patt.test(email))
                        alert("Valid Address Email");
                    else
                        alert("Invalid address Email");
                }
                else
                    alert("Email is Empty : Valid Address Email");
                    
            }
            
            
        </script>
    </body>
</html>
Ehsan
  • 12,655
  • 3
  • 25
  • 44
0

Check links

<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)@(\w+\.)+(com|kr|net|us|info|biz)" required="required">

Ranjan
  • 929
  • 1
  • 6
  • 19