Skip to content

Exploring Validation JS

PRASHANT KUMAR edited this page Jul 8, 2017 · 7 revisions

This plugin is based on jQuery library and helps in validating html forms. Plugin provides default error messages which can be customised.

Documentation

Understanding error classes

Plugin Options and Overriding defualt error messages

Refreshing data and bindings

Adding custom error messages

Adding custom rules to plugin

Understanding error classes

(Will be updated soon)

Plugin Options and Overriding defualt error messages

Plugin Option with their default values are shown below. Options can be passed as second argument of "validationJs(selector, option)" function.

{
        messaging:true,
        formErrorClass: 'error',
        preventSubmitOnError: true,
        dateFormat: 'yyyy/mm/dd',
        sevarErrorMsg: "Server validation failed!",
        getErrorElement:undefined,
        fieldSuccessCallback: undefined, //callback will get refrence of field as first parameter
        fieldErrorCallback: undefined,  //callback will get refrence of field as first parameter and error type as second parameter
        formSuccessCallback: undefined, //callback will get refrence of form as first parameter
        formErrorCallback: undefined,  //callback will get refrence of form as first parameter
        noValidateClass: 'novalidate',
        errorClass: {
            required: "isRequired", 
            phone:  "isPhone",
            integer: "isInteger",
            number: "isNumber",
            decimal: "isDecimal",
            digits: "isDigits",
            email:  "isEmail",
            url: "isUrl",
            date: "isDate", 
            regex:  "isRegex",
            char:  "isChar", 
            length: "isLength",
            alphaNumeric: "isAlphaNumeric"   
          },
        errorMsg: {
            required: "This is required field!",
            char: "This field can contain characters only!",
            phone: "Phone Number should be a Number of 10 digits!",
            integer: {
                int_msg: "This field can contain integer only!",
                min_msg: "Minimum value for this field is: ",
                max_msg: "Maximum value for this field is: ",
                min_max_msg: "Minimum and Maximum values for this field are: "
              },
            number: {
                num_msg: "This field can contain numbers only!",
                min_msg: "Minimum value for this field is: ",
                max_msg: "Maximum value for this field is: ",
                min_max_msg: "Minimum and Maximum values for this field are: "
              },
            decimal: {
                dec_msg: "This field can contain decimal only!",
                min_msg: "Minimum value for this field is: ",
                max_msg: "Maximum value for this field is: ",
                min_max_msg: "Minimum and Maximum values for this field are: "
              },

            digits: "This field can contain numbers only!",
            date: {
                date_msg: "This field has Invalid Date Format or Value!",
                min_msg: "Minimum date value for this field is: ",
                max_msg: "Maximum date value for this field is: ",
                min_max_msg: "Minimum and Maximum date values for this field are: "
              },
            email: "Invalid Email Id!",
            url: "Invalid Url!",
            regex: "Field do not match required pattern!",
            length: {
                min_msg: "Minimum length for this field is: ",
                max_msg: "Maximum length for this field is: ",
                min_max_msg: "Minimum and Maximum length for this field are: "
              },
            alphaNumeric: "Only alphanumeric charecters allowed!"
        }
    }
  

Example:

var app = new validationJs(#myForm”, {messaging:false, formErrorClass: 'custom-error-class'});

Refreshing data and bindings

Some times we need to refresh bindings of elements. Such cases are:

  • When we add input fields at run time(validation time).
  • When we rerender the input field (may be after server side validtion)

We can refresh the bindings whenever we found the case where binding may break.

var app= validationJs(#myForm”);
app.refresh(); //this will refresh all bindings(form and inputs)

Adding custom error messages

Method: addErrorMsg()

Parameters: Object/Array of Object

Discription:

Suppose you have "First Name" field in the form and you want to show a customized error message like:

When required error occurs: First Name is required!

When someone enters number: First Name should only contains alphabatical character!

To achieve this you need to do following:

  1. Add a selector to the concerned input(may be ID or Class)
  2. Add error classes to input fields
  3. Create message object: rule name(rule name can be obtained by removing "is" from error class string and making first charecter of remaining string as lowercase) as Key and conerned message as Value.
  4. Now create another object with key as the selector of your input and value as a message object.
  5. Add this new object to your app object by using addErrorMsg() Method.
<input type="text" id="first_name" class="isRequired isChar" />
<span class="error"></span>
var app=validationJs("#myform");
var first_name_msg={
						"required": "First Name is required!",
                        "char":	"First Name should only contains alphabatical character!"
                   };
app.addErrorMsg({selector: "#first_name", msg: first_name_msg}); //function can accept single object or array of such objects

To add similler error messages to samillier type of fields use class as selector. For example your form has to emails, primary and secondary, and you want to provide common custom error messages.

To achieve this you need do following:

  1. Add a selector (class) to all concerned inputs (for both emails in this case, say "cstm-email").
  2. Add error classes to input fields
  3. Create message object: rule name(rule name can be obtained by removing "is" from error class string and making first charecter of remaining string as lowercase) as Key and conerned message as Value.
  4. Now create another object with key as the selector of your input and value as a message object.
  5. Add this new object to your app object by using addErrorMsg() Method.
<input type="text" id="first_name" name="first_name" class="isRequired isChar" />
<span class="error"></span>

<input type="email" name="primary_email"  class="cstm-email isRequired" />
<span class="error"></span>

<input type="email" name="secondary_email"  class="cstm-email isRequired" />
<span class="error"></span>
var app=validationJs("#myform");
var first_name_msg={
						"required": "First Name is required!",
                        "char":	"First Name should only contains alphabatical character!"
                   };
var email_msg={
					"required": "Email is required field, and this is first custom error message",
         			"email": "Email is invalid, and this is second custom error message"           
				};
app.addErrorMsg([
					{selector: "#first_name", msg: first_name_msg},
                    {selector: ".cstm-email", msg: email_msg}
                    
                ]); //function can accept single object or array of such objects

NOTE: If you use multiple selectors(classes or ids) to customize error message, post message object in array will override the previous message object.

Adding custom rules to plugin

Method: addRule()

Parameters:

  1. Rule Name (String)

  2. Error Class (String)

  3. Error Message (String/Object)

  4. Callback Function

Discription:

All parameters are required.

Rule Name is used to create a custom rule with the provided name and used by the plugin.

Error Class is the class you need to add in your input element. To maintain uniqueness in error class, you should create it by adding "is" prefix in rule name (ex: for rule name "customRule" use "isCustomRule" as error class).

Error Message can be String (say Case 1) if you want to show single message in all condition for your custom rule. If you want to show different messages depending upon condition use Object format (say Case 2). Ex: {error_1: "age can not be more than 150", error_2: "age can not be less then 0"}.

Callback Function contains your logic where you make decision for correct/incorrect input. It has three arguments, which contains:

  1. Input field reference (ref)

  2. Input field value and (val)

  3. Message Object (msgObj): For Case 2, It can be modified if needed.

Note: If parameter "Error Message" is String you need to return true/false in callback function for valid/invalid inputs respectively. And if it is in Object format return an Object in callback function in following format:

For Valid input: {status:true}

For Invalid input: {status:false, type: "error_msg_key_of_message_obj"}

EXAMPLE (Case 1/Error Message parameter as String):

var app=validationJs("#myform");

//app.addRule(Rule_Name, Error_Class, Error_Message, Callback_function);

app.addRule("customRule", "isCustomRule", "Age is invalid (error message from customRule)", function(ref, val){
  /*
      "ref" contains the input element ref
        "val" contains the input value
    */
  if(val>0 && val<150)
      return true;
    else
      return false;
});

EXAMPLE (Case 2/Error Message parameter as Object):

var app=validationJs('#myform');

var errorMsg={
        error_1: "Age can not be more than 150",  
                error_2: "Age can not be less then 0"
            };

//app.addRule(Rule_Name, Error_Class, Error_Message_object, Callback_function);

app.addRule("customRule", "isCustomRule", errorMsg, function(ref, val, msgObj){
  /*
      msgObj is the copy of Error_Message_object (here errorMsg) used by the plugin. You can modify it if you need.
    */
    if(val>150)
      return {status:false, type:"error_1"};
    else if(val<0)
      return {status:false, type:"error_2"};
    else
      return {status:true};
});

How to use custom rules?

Custom rule will be used similar to the native plugin rules. For example:

<input name="age" class="isInteger isCustomRule"/>
<span class="error"></span>