jQuery Validation : Special Features Document

Order of the rules definition matters

# in CoffeeScript
"user[password_confirmation]":
  required: true
  equalTo: $('#user_password')
  minlength: 8
  maxlength: 16

and this behave different

# in CoffeeScript
"user[password_confirmation]":
  required: true
  minlength: 8
  maxlength: 16
  equalTo: $('#user_password')

the former one validates the password length at last, whereas later one validates integrity.

Highlight / Unhighlight

Can highlight fields and unhighlight when field is valid.

# in CoffeeScript
highlight: (element) ->
  $(element).closest('.form-group').addClass 'has-signup-error'
  return
unhighlight: (element) ->
  $(element).closest('.form-group').removeClass 'has-signup-error'
  return

 

# in CoffeeScript
# Trigger validation when focus is lost from the field
$(".new_user input, .new_user select").focusout (element) ->
  $el = $(this)
  if !$el.is('select') and element.value == '' and element.defaultValue == ''
    # for untouched text fields, don't validate on blur
    return
  $el.valid()
  return

 

you can also customize the regex to validate email fields

$.validator.methods.email = function( value, element ) {
  return this.optional( element ) || /[a-z]+@[a-z]+\.[a-z]+/.test( value );
};

See https://jqueryvalidation.org/jQuery.validator.methods/

 

Validation of hidden fields

This feature will be useful specially for checkbox. You usually decorate your checkboxes and radios using CSS and hide the original input field. By default jQuery Validation skips validation of hidden items.

You can use the :not() selector combined with :hidden to activate validation for specific hidden items:

ignore: ":hidden:not(.my_item)"

Example:

$('.edit_vehicle_owner').validate({
  ignore: ":hidden:not(#vehicle_owner_agreed_to_terms_and_condition)",
  
  rules: {
    "vehicle_owner[first_name]": {
      required: true
    },
    "vehicle_owner[agreed_to_terms_and_condition]": {
      required: true,
    }
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s