Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation plugin - check if field is valid (but not show the validation message)

I am using jQuery validation plugin and have defined a form validation function as shown below. Based on some user action I am running a custom JS function and in that function I just want to check whether the email and phone fields are valid. But I don't want to validate them i.e. I don't want to show the validation errors, I just need to check if their value is valid.

Something like

$('#email').isvalid();

I have checked out the element method of Validator but that validates the element rather than just checking if it's value is valid. So In other words I am looking for a way to run the rules programmatically. Any help is appreciated!

Form validator function below:

var validator = $("#olForm").validate({
    rules: {
        "email": {
             required: true,
             email: true
        },
        "phone": {
             required: true,
             digits: true,
             minlength: 9,
             maxlength: 11
        }
    }
});
like image 443
arahant Avatar asked Sep 18 '12 15:09

arahant


People also ask

Why jQuery validation is not working?

Your answer The "$(...). validate is not a function" jQuery error occurs when the jQuery validation plugin is not loaded or the jQuery-related scripts are loaded in an incorrect order. The validation plugin should be loaded after the jQuery library.

How remove validation after field is valid using jQuery?

$("form"). validate(). resetForm();

How do you check if a form is validated?

Using the email type, we can check the validity of the form field with a javascript function called… checkValidity() . This function returns a true|false value. checkValidity() will look at the input type as well as if the required attribute was set and any pattern="" tag .

What is valid () in jQuery?

valid()Returns: Boolean Description: Checks whether the selected form is valid or whether all selected elements are valid.


2 Answers

There is an undocumented method check() that does this specifically without actually styling the fields or showing any errors:

var validator = $('form').validate();
if( validator.check('#email') ){
  // this field is valid but no styling was applied
}
like image 177
Dan H Avatar answered Oct 24 '22 05:10

Dan H


There is a handy method called .checkForm() (undocumented as of September 2015), which makes this really easy. Unlike calling .valid(), this won't show form errors when it's called:

// Returns a boolean
$('form').validate().checkForm();
like image 37
rnevius Avatar answered Oct 24 '22 03:10

rnevius