Multiple case validation using jquery validation plugin

837 views Asked by At

I have created the following login form in html and validation has been done using jquery validate plugin. http://jqueryvalidation.org/ Here , I am validating the whole login form when the login button is clicked.

    <form method="POST" id="LoginForm">
        <label>Email</label>
        <input type="text" id="user_Email" name="user_Email" />
        <br>
        <label>Password</label>
        <input type="password" id="user_Pass" name="user_Pass" />
        <br>
        <input type="button" value="Login" id="btnLogin">
    </form>

validation script

$("#LoginForm").validate({
    rules: {
        user_Email: {
            required: true,
            email: true
        },
        user_Pass: {
            required: true
        }
    },
    messages: {
        user_Email: {
            required: "Email is required",
            email: "Enter a valid email address"
        },
        user_Pass: {
            required: "Password is required"
        }
    }
});
$('#btnLogin').click(function() {
    var form = $('#LoginForm');
    if (form.valid()) {
        // submit the form data
    }
});

Like validating the whole form with error labels when the button is clicked , I also want to validate only the email field without error labels and error classes for another case. When user entering a email address i want to validate the validity of the email address(true or false) without validating the whole form and without displaying the error label.Just the validity. How to achieve this using jquery validation plugin. I tried it jquery input text change event, but it does not work.

$('#user_Email').on('input',function(){
    //check for a valid email address on text change of email input
})

Please help me in this. Thank you.

2

There are 2 answers

2
Vishnu Prasad On

Add this

$( "#user_Email" ).focusout(function() {
  var re    = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  var email = $("#user_Email").val();
  if(!re.test(email)) {
      //give proper valodation message here
      alert("Invalid Email...!!");
      $("#user_Email").focus();
      }
});

This will show alert message when invalid email addess is given andd pass to next next field and cursor will back in email field

EDIT

As per your comment the validation with http://jqueryvalidation.org/ for one single field (email) is shown below.

  $('#btnLogin').click(function() {
        if($("#LoginForm").validate().element($("#user_Email"))){
        //give proper valodation message here
        alert("Invalid Email..!!");
        }
    });

Enjoy coding... :)

0
suraj mahajan On