robins
robins

Reputation: 1668

How to check email validation using JavaScript?

I want to check my field is nil, then return true otherwise check email validation. My field name is app_email.

$.validator.addMethod("checkEmail", function(app_email, element) {
        var result;
        if (condition) {
            result = (app_email === "NIL") ? true : false;  
        } else {
            preg_match( /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/,app_email);
            return true;
        }
    }, 
    "Email id is not valid."
);

html

                      <div class="control-group">
                       <label class="control-label">E-mail ID<span class="required">*</span></label>
                            <div class="controls">
                                  <input type="text" class="span6 m-wrap"  name="app_email" title="Enter Email Id">  
                            </div>
                       </div>

Upvotes: 1

Views: 211

Answers (2)

jmvtrinidad
jmvtrinidad

Reputation: 3658

If you are using jQuery Validation, you can use the default function like this.

You can refer to this link.

$( "#myform" ).validate({
  rules: {
    fieldNameHere: {
      required: true,
      email: true
    }
  }
});

Check if the value is 'NIL' return true, otherwise, validate email.

$.validator.addMethod("checkEmail", 
    function(value, element) {
        return value === "NIL" ? true : /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(value);
    }, 
    "Email id is not valid."
    );

Upvotes: 2

H&#252;seyin BABAL
H&#252;seyin BABAL

Reputation: 15550

Demo

You can use radio button check inside custom validation like below.

JS:

jQuery.validator.addMethod("checkEmail", function (value, element) {
        if ($('input:radio').is(':checked')) {
            if (/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/.test(value)) {
                return true;
            } else {    
                return false;
            }
        } else {
            return true;
        }
        
    }, "Email id is not valid.");

    $('#myform').validate({
        rules: {
            email: {
                checkEmail: true
            }
        }
    });

HTML:

<form id="myform">
    <input type="radio" value="">
    <input name="email" id="email" type="text"/>
    <input type="submit" />
</form>

In this example, email validation will be perform if the radio button is selected.

Upvotes: 2

Related Questions