<commit_before>---
layout: post
title:  "jquery Validation addMethod()"
date:   2015-01-29 12:34:25
categories:
tags: jquery-validation
#image:
published: true
---

#An example of addMethod()

In a use case where I have to compare an input with another input,
jQuery Validation Plugin provides a helper method `addMethod` to write my own validator.

Example:
I created a form to ask user to enter his/her current age and retirement age, and retirement age must be greater current age.

See [addMethod notation](http://jqueryvalidation.org/jQuery.validator.addMethod/).

[Demo](http://jsbin.com/covawaboxi/1/edit?html,js,output)

(for brevity, I stripped all the unnecessary html attributes)

```html
<form>
    <label>Current Age</label>
    <input id="age" type="number" name="age" required value="60"><br>
    <label>Age At Retirement</label>
    <input type="number" name="ageAtRetirement" required value="50"><br>
    <input type="submit" value="check">
</form>
```


```javascript
$.validator.addMethod('greaterThan',
    function(value, element, params){
        // It must returns a true or false.
        // A false value will invokes error message
        return value > $(params).val();
    },
    // default error message
    'The age when payments begin must be greater than the current age. ');


var validationConfigs = {
    rules: {

      ageAtRetirement : {  // input name attribute
        name of the method created above, and `#age` is id of the input field `age`
        greaterThan : '#age'
      }
    },
    // customize error messages
    messages: {
      ageAtRetirement : { // for ageAtRequirement input
        // error message when retirement age is smaller than current age
        greaterThan : 'Retirement age must be greater than current age'
      }
    }
  };

// to run **Validation** with the rules above,
// pass the configs object `validationConfigs` in the `validate()` param
$('form').validate(validationConfigs);
```



# Bonus: validate input value on blur, and add classnames

Validation has many other events: **onsubmit, onfocusout**,etc. These events are configurable in the similar fashion as `rules` above.
To validate an input as soon user moves away from the input field, add `onfocusout` method, and use `element()` method to validate the
that input.

```javascript

var validationConfigs = {
    onfocusout: function onfocusout(input, event){
        this.element(input);
    },
    rules: {.... },
    messages: {...}
}
```

[Demo](http://jsbin.com/jiqidoruja/1/edit)

For other things such adding my own classnames for errors or valid inputs,
see `errorClass`, `validClass`, `highlight`, `unhighlight`, `errorPlacement` on this page <http://jqueryvalidation.org/validate/>


<commit_msg>update jquery validation post<commit_after>---
layout: post
title:  "jQuery Validation addMethod()"
date:   2015-01-29 12:34:25
categories:
tags: jquery-validation
#image:
published: true
---

I wrote a few jQuery plugins for form validation in the past, most of them provided the same functions, and varied a bit depends on the projects.
jQuery validation covers many of the common usages, for anything else there's an addMethod() to provide my own form validation.


#custom validation with addMethod()

In a project, I have an input form to make sure the user enters his/her retirement age must be greater than his current age.

[See addMethod notation](http://jqueryvalidation.org/jQuery.validator.addMethod/).

[Demo](http://jsbin.com/covawaboxi/1/edit?html,js,output)

(for brevity, I stripped all the unnecessary html attributes)


```html
<form>
    <label>Current Age</label>
    <input id="age" type="number" name="age" required value="60"><br>
    <label>Age At Retirement</label>
    <input type="number" name="ageAtRetirement" required value="50"><br>
    <input type="submit" value="check">
</form>
```


```javascript
$.validator.addMethod('greaterThan',
    function(value, element, params){
        return value > $(params).val();  // It must returns a boolean, true: passed or false: failed.
    },
    'The age when payments begin must be greater than the current age. ');  // default error message


var validationConfigs = {
    rules: {
      ageAtRetirement : {  // input's attribute name
        greaterThan : '#age' // greaterThan: is the name of the method, #age: if the inputs to compare
      }
    },
    // customize error message
    messages: {
      ageAtRetirement : {
        greaterThan : 'Retirement age must be greater than current age'
      }
    }
  };

$('form').validate(validationConfigs);
```

#validate onfocusout, onkeyup, onsubmit...

What about if I want to validate an input field as soon user moves to the next input field (onfocusout)? Or validate characters while user's typing?
jQuery Validation supports these events, it can be easily configured in the object like the example below.


```javascript
var validationConfigs = {
    onfocusout: function onfocusout(input, event){
        this.element(input);
    },
    rules: {.... },
    messages: {...}
}
```

[Demo](http://jsbin.com/jiqidoruja/1/edit)


#Error message placement, add or remove classes


`highlight`: it's being used to add error classes etc. an input failed validation
`unhighlight`: when an input passed validation, use this method to remove previous error classes
`errorPlacement`:

```javascript
var validationConfigs = {
      highlight: function(element, errorClass, validClass) {
        $(element)
          .closest('.form-group')
          .addClass('has-error');
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element)
          .closest('.form-group')
          .removeClass('has-error');
      },
      errorPlacement: function(error, element) {
        var $element = $(element);
        $element.parent().append(error);
      }
   }
};
```

See docs: <http://jqueryvalidation.org/validate/>



{'fraction_non_alphanumeric': 0.11727872736503639, 'fraction_numerical': 0.006769334912844813, 'mean_word_length': 3.4840667678300457, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3099156', 'n_tokens_mistral': 1721, 'n_tokens_neox': 1635, 'n_words': 616}