Skip to content
This repository has been archived by the owner on Sep 21, 2023. It is now read-only.
Rogério Taques edited this page Nov 9, 2016 · 6 revisions

Introduction

Learn how to use the Valida in detail.

This docs are about v.2.1.x.

Since your are using the jQuery Valida, the form you set to use it will be filled with some stuff to improve the experience of your user on your app or website.

  • Each TEXTAREA, on your form, which has a maxlength property set, will receive a description label (right below it) that displays the maxlength and how many chars were already typed!

  • Each INPUT text field, on your form, which has a filter property set, will be analysed when the user is typing to inform him/her that the value is valid or invalid!

  • During the validation process, each field on your form which has the "required" property set and has no value or has the "filter" property set and the value doesn't match the given filter, will receive a label (right below it) with a error/invalid message.

  • You also can run some stuff before/after the validation via callback methods and customize the messages and the layout of messages displayed!

On this doc, I'm assuming that you have a minimal knowledge about web development, so, I won't carry about details, just focusing on Valida features.

##1. Download the latest version of Valida & jQuery

First at all you need take the last stable version of:

After download it, put it on your app root folder, or whenever folder you need, inside your app structure of folders.

  - / (this is your app root folder)
  --- jquery.js
  --- valida.js
  --- index.html

2. Importing the libraries

Add the code below into the HEAD section on your page. Note that you also MUST import the jQuery library.

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="valida.2.0.7.min.js"></script>

Your index.html might look like this:


  <!DOCTYPE html>

  <html >
    <head >
      <title>My first page with jQuery Valida Plugin</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="valida.2.0.7.min.js"></script>
    </head>
    <body >
       <p >This is my form!</p>
       <form name="form-1" method="post" action="your-action-here" >
         <p>
	   Field 1: <br />
           <input type="text" name="field-1" id="field-1" required="true" />
         </p>
         <p>
           Field 2: <br />
	   <input type="text" name="field-2" id="field-2" filter="email" />
         </p>
         <p>
           Field 3: <br />
	   <select name="field-3" id="field-3" required="required" >
	     <option value=""></option>
             <option value="val-1">Value 1</option>
	     <option value="val-2">Value 2</option>
	   </select>
	 </p>
	 <p>
	   Field 4: <br />
	   <textarea name="field-4" id="field-4" required="required" maxlength="10" ></textarea>
	 </p>
	 <p>
	   <input type="submit" name="sub-1" value="Submit 1" />
	   <input type="reset" name="res-1" value="Reset 1" />
	   <input type="button" name="but-1" value="Button 1" /> <br />

	   <button type="submit" name="sub-2">Submit 2</button>
	   <button type="reset" name="res-2">Reset 2</button>
	   <button type="button" name="but-2">Button 2</button>
 	 </p>
       </form>
    </body>
  </html>

3. Setting up Valida

Now, we might setup Valida to it automatically validate your forms.

To do it, there are 2 different ways, as below:

3.1. Simple call

For each form you have in your page, you can apply this code:

  $('#form-1').valida();
  $('#form-2').valida();
  ...
  $('#form-N').valida();

Now, click on any submit button to see what happen! ;)

3.2. Full call

For each form you have in your page, you can apply this code:

  $('#form-1').valida({
       form_validate: 'novalidate',
       form_autocomplete: 'off',
       tag: 'p',
       lost_focus: true,
       highlight: {
           marker: '*',
           position: 'post'
       },
       messages: {
          submit: 'Wait ...',
	  required: 'Required field',
	  invalid: 'Field with invalid data',
	  textarea_help: 'Typed <span class="at-counter">{0}</span> of {1}'
        },
	use_filter: true,
	before_validate: null,	// callback which runs before default validation
	after_validate: null	// callback which runs after default validation
		
   });

Now, click on any submit button to see what happen! ;)

4. Available options

So, now that we already know how to import and setup the Valida, it's time to learn which are the available options to set it up!

4.1. form_validate

It's a string value. Default 'novalidate'.

When 'novalidate', Valida will set the "novalidate" property of your form. It means that the browser will not be concerned about the field validations before submit your form.

It's a HTML 5 feature.

4.2. form_autocomplete

It's a string value. Default 'off'.

If set to 'off', Valida will set the "autocomplete" property of your form to "off". It means that the browser will not display the values in auto complete mode, stored before.

Available options are: 'on'/ 'off'

It's a HTML 5 feature.

4.3. use_filter

It's a boolean value. Default TRUE.

If set true, Valida will check the field filters in each submit made.

So, if you set a filter for your field, this options must be set to TRUE, or, just not supplied!

Example:

On your javascript code:

  $('#form-1').valida({
    use_filter: true
  });

On your HTML code:

  <input type="text" ... filter="email" />

After v.1.2 you can set up more than only 1 filter using pipes. This allow you to combine a range of filters to make a smarter and faster validation of the fields of your form.

Example:

Let's assume that you have a field which need to be filled exclusively with a value between 10 and 20. On this case, you just need to set up the filter tag of your field such as the example bellow:

  <input type="text" ... filter="less_than:20|greater_than:10" />

Note that we used the notation filter_name:length.

Valida can also verify for you if some fields has the same value. This feature is very usefull when there is a password field on your form. It's a good option to also insert a password verification field, to make sure that your user has no typed his/her password wrong!

Example:

  Insert your password: <br />
  <input type="password" ... id="passwd" /> <br />

  Confirm your password: <br />
  <input type="password" ... id="passwd-confirm" filter="matches:passwd" />

Note that we used the notation matches:id_of_field. The id_of_field is the ID of the field which the value MUST match.

4.4. Available Filters

Most of all filters are in regular expression validation. Since v.1.2, we've also implemented the Functional Filters. This new filters make possible smarter validations.

Currently, the below filters are available:

Since Filter Example/Notation Remark
email name@domain.com
v1.1 url http://google.com
number 0123456789
decimal 1,234.56 or 1.234,56
date_br 25/01/2012
date 2012-01-25
time 22:45
phone_br (12) 3456-7890 or (12) 93456-7890 Updated (v1.3.6) to support the 9th digit of brazilians mobile phone numbers
phone_jp (0123) 45-6789 or (123) 4567-8901
zipcode_us A1B2C3
zipcode_br 12345-678 or 12.345-678
zipcode_jp 123-4567
v1.2 valid_ip from 0.0.0.0 to 255.255.255.255
min_length min_length:value
max_length max_length:value
matches matches:field_id
greater_than greater_than:value
less_than less_than:value
v2.1.7 cpf cpf:field_id Thanks to Eduardo Barros who has requested this
v2.1.7 cnpj cnpj:field_id

Want to see your regular expression filter here? Send me a pull request! ;)

5. Available events

You, also, can fire your own validations before/after the Valida process be started/ finished! It's very useful when you need to proceed with some special or alternative validations.

5.1. before_validate(event)

To run something BEFORE Valida start it's process, you just can provide a before_validate callback function.

Your callback function will receive a parameter with the window.Event and MUST return a boolean (TRUE/FALSE).

The return will be used for Valida to proceed validation on your form.

For example:

  $('#form-1').valida({
    before_validate: function(e) {
      alert('Hello World! Before validation.');
      return true;
    }
  });

5.2. after_validate(event, boolean)

To run something AFTER Valida start it's process, you just can provide a after_validate callback function.

Your callback function will receive 2 parameter. The first will be window.Event and the second will be a boolean that represents the error status of validation. If the second parameter is TRUE, means that the validation doesn't pass on test.

Your callback MIGHT return a boolean (TRUE/FALSE).

It's important to notice that when your callback function will return, the return results MUST be the opposite of the error status received. It happen because Valida uses the result of your callback to define if the form doesn't pass on your custom validation.

If your form has passed (and every thing is OK to send the form data to the server), then your return MUST be TRUE. Otherwise, your MUST return FALSE.

For example:

  $('#form-1').valida({
    after_validate: function(e, err) {
      alert('Hello World! After validation.');
      if (err) {
         alert('Something goes wrong before.');
      }
      return !err; // invert the error status
    }
  });

6. Available methods

Some additional methods were created to help you manage your form validations.

6.1. Destroy

It's possible to destroy any instance of Valida using this additional method.

To destroy a previous set instance, just call:

   $('#form-1').valida('destroy');

Then you can initialize a new instance of Valida with different options.

6.2. Partial Validation

Some times it's necessary to validate only a portion of your form, for example, when your form is sliced in many layers (or steps) and you should validate those fields that are visible to user before go forward to next step.

To partial validate your form, use the 'partial' method. To call it use:

    var result = $('#form-1').valida('partial', '#field-id');

Result will be:

  • TRUE = Valid
  • FALSE = With errors

Further, you can pass other 2 additional parameters:

    var result = $('#form-1').valida('partial', '#field-id', true, true);

The first, instruct Valida to automaticaly show error messages, whenever it has one. By default it's set to true.

The second, instructs Valida to clear previous error messages before place a new one. By default it's set to true.

7. Customizing

For sure you can customize it.

On standard mode, the messages will be displayed in English, but you can always translate it to your main language on an easy way.

7.1. Translating Messages

There are 2 ways to provide a translated message for Valid uses.

You can provide a default message, such as the example below:

  $('#form-1').valida({
		messages: {
			// when a submit button is clicked
			submit: 'Wait ...',
			// when there is a required field unfilled
			required: 'Required field',
			// when there is a invalid value for a filtered field
			invalid: 'Field with invalid data',
			// when there is textareas with maxlength set
			textarea_help: 'Typed <span class="at-counter">{0}</span> of {1}'
		}
  });

Or, for error and invalid messages, you can provide a different message for each field you may have on your form. This kind of customization is useful even when you want put a special message for some field. For example:

  <input type="text" ... required="true" data-required="Please, fill this field!" />
  <input type="text" ... filter="email" data-invalid="You must provide a valid e-mail address!" />

Valida will always look for individual messages before set the default messages. So, you'll be able to provide both.

7.2 Layout customization

To help you for layout customization, some classes are provided to be used on your CSS rules.

This classes are:

  <style type="text/css" >
    /* applyed for error labels */
    .at-error {}

    /* applyed for invalid labels */
    .at-warning {}

    /* applyed for information labels - not available on this version yet! */
    .at-info {}

    /* applyed for required fields */
    .at-required {}

    /* applyed for invalid fields */
    .at-invalid {}

    /* applyed for textarea char-count label */
    .at-description {}

    /* 
      applyed for any SPAN tag into textarea char-count labels 
      this span tags has the numbers of maxlength & char typed.
    */
    .at-description > span {}
  </style>

8. Known Issues

This version doesn't work properly with IE less then 7. In some cases, when validating what the user type, an error is thrown by jQuery, cause it can't manage to resolve the source object!

For while, to fix it, keep in mind to create a fall-back function that not instantiate Valida when the user is navigating with IE < 7!


That's it! Easy, don't you?

Feel free to leave a comment.

Happy coding! =)