Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to do CSS Masking?

See in this article how to use jQuery Validation Framework for creating web forms validation.

A key step in developing a web application is a form validation since it is at this stage where we define what restrictions or validations the form must meet, thus ensuring that users provide only valid data. Thus, there are two popular types of form validation, the client-site (validations that occur on the client side) and server-side (validations that occur on the server side). However, this article focuses only on the client-side, where we use the jQuery Validation Framework for the validation of web forms.

jQuery Validation Plugin

Developed in 2006 by Jörn Zaefferer (founding member of jQuery), the Validation Plugin in its current version 1.14.0 and allows the developer to create validations in a simple form, providing a set of useful methods of validation such as required field, number of credit card, URL, email and others, in addition, it provides an API for creating our own custom validation methods. And for exhibition of messages (error and success) to the user during validation, the Validation plugin offers over 37 translations, including standard English, and others.

To begin with the jQuery Validation is pretty simple, justcreate a file called "index.html" and add the code in Listing 1 .

Listing 1. Code of index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Validating forms with jQuery Validation</title>
    <!-- Boostrap CSS files -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" />
</head>


<body>
    <div class="container">
        <h2>Please, fill all the fields</h2>
        <form role="form" method=''post'' id=''formComments''>
            <p>
                <label for="cnome">Name (required, at least 2 characters)</label>
                <input type="text" class="form-control" placeholder=''Enter Name'' id="cnome" name="nome" required minlength="2">
            </p>
            <p>
                <label for="cemail">Email (required)</label>
                <input type="email" class="form-control" placeholder=''Enter Email'' id="cemail" name="email" required>
            </p>
            <p>
                <label for="ccomentario">Your comments (required)</label>
                <textarea id="ccomentario" class="form-control" placeholder=''Enter Comments'' name="comentario" required></textarea>
            </p>
            <p>
                <button type="submit" class="btn btn-default">Submit</button>
            </p>
        </form>
    </div>
    <!-- jQuery -->
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <!-- Plugin jQuery Validation -->
    <script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
    <!-- Bootstrap plugin JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <!-- Validations with the Plugin jQuery Validation-->
    <script src="validation.js"></script>
</body>


</html>

After that, just create a new JavaScript file called "validation.js" with code of Listing 2 where we can find the code of our first validation using the plugin.

Listing 2. Code of validation.js file.

// A simple validation
$("#formComments").validate();

Note that in this code, with only one method we can validate the whole form. The "#formComments" references our form where we declared in tag the id=''formComments''. This way the Validation plugin can understand it will validate each field according with its specificity, e.g, once our email field is marked with type=''email'' and required, the Validation will only allow a valid email entry and ask always for its filling.

To see the validation workign, just access the form in the browser and try to see the form clicking on the button "Submit", then we''ll have a result similar to Figure 1 .

Figure 1. Result of our form validation using Validation Plugin

And then we create our first form validation page with Validation Plugin.

Working with validate() method from Validation Plugin

In this section we will know the main validation options to validate() method, see:

  • debug: This option can be set as true or false, if we define as true, the plugin will not allow the submission of the form, even if all the data is valid, if set to false will allow sending data. This option is interesting when we want to perform some type of test.
  • messages: With this option we can define custom messages for each rule set for each field, thus performing an "override" of the messages taken as standard from Validation Plugin. However, it is noteworthy that the Validation provides in your repository messages in a lot of languages.
  • rules: This option is where we define the validation rules for each field of our form. Consider the following key validation rules:

The following rules are present in the script of Listing 1

Regra

Validação

email

If true, the field will only accept valid emails

required

If true, the field is required

min

Define a number or minimum valid value. For example, if we define as 4, the user can only inform a number bigger or equal to 4, less than this the information is invalid.

max

Define a number or maximum valida value. For example, if we define as 10, the user can only inform a number less or equal lto 10, bigger than this the information is invalid.

range

Determine an interval, containing a minimum and maximum values valid. For example, if we define as [10, 20], the user only can inform a number bigger or equal to 10 and less or equal to 20

minlength

Determine a minimum quantity of chars. For example, if we define as 10, the user can only inform a value with at least 10 characters, less than this the information is invalid.

maxlength

Define a maximum quantity of characters. For example, if we define as 5, the user can only inform a value up to 5 characters. Bigger than this, the information is invalid.

rangelength

Define an interval, containing a minimum and maximum quantity of valid chars. For example, if we define as [2, 6], the user can only inform a value with at least 2 and up to 6 characters

url

If we define as true, the field will only accept valid urls

date

If we define as true, the field will only accept valid dates

dateISO

If we define as true, the field will only accept dates in ISO format

number

If we define as true, the field will only accept integer or decimal numbers

digits

If we define as true, the field will only accept digits

creditcard

If we define as true, the field will only accept valid credit card numbers

remote

If we define a verification url, for example “check_if_id_exists.php”. The, Validation will perform a remote check with the url and the value informed in the field, then, if the response to the request is false, then the Validation understands that the information in the field is not valid. In the other hand, if the response is true then the information is valid.

equalTo

Check if the values of both fields are equal. For example: check if both passwords are equal, when trying to insert a password e repeat it again.

accept

This rule is used to the field “input= file” to upload a file where we can define what mime-types are allowed. For example, if we define this rule with a value “audio/*”, then we''re saying to the Validation that only audio files are allowed.

extension

Here we can define a certain file extension that can be accepted;

phoneUs

If defined as true, the field will only accept a phone value of the EUA

require_from_group

Assure at least one field must be valid inside of a fields group.

Now we will make a form validation example using some rules outlined in this section. To this, add the code in Listing 3 to the "index.html" file.

Listing 3. index.html code page

<!DOCTYPE html>
<html lang="en">


<head>
    <meta charset="UTF-8">
    <title>Validating forms with jQuery Validation</title>
    <!-- Boostrap CSS files -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" />
    <style>
        .error {
            color: red;
        }
    </style>
</head>


<body>
    <div class="container">
        <h2>Validation options of validate() method from jQuery Validation plugin</h2>
        <form id="formValidation">
            <p>
                <label for="field1">Rules: required, email and remote </label>
                <input class="form-control" type="email" id="field1" name="field1">
            </p>
            <p>
                <label for="field2">Rules: minlength, maxlength and rangelength </label>
                <input class="form-control" type="text" id="field2" name="field2">
            </p>
            <p>
                <label for="field3">Rules: min, max and range </label>
                <input class="form-control" type="text" id="field3" name="field3">
            </p>
            <p>
                <label for="field4">Rules: accept </label>
                <input class="form-control" type="file" id="field4" name="field4">
            </p>
            <p><b>Phone Group, where at least one must be valid</b>
                <br/>
                <label for="personal_phone">1º require_from_group: Personal Phone: </label>
                <input class="phone_group form-control" id="personal_phone" name="personal_phone">
                <br/>
                <label for="phone_home">1º require_from_group: Home Phone: </label>
                <input class="phone_group form-control" id="phone_home" name="phone_home">
                <br/>
                <label for="phone_work">1º require_from_group: Work Phone: </label>
                <input class="phone_group form-control" id="phone_work" name="phone_work">
            </p>
            <button type="submit" class="btn btn-default">Validate!</button>
        </form>


    </div>
    <!-- jQuery -->
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <!-- Plugin jQuery Validation -->
    <script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
    <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
    <!-- Bootstrap plugin JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <!-- Validations with the Plugin jQuery Validation-->
    <script src="validation.js"></script>
</body>


</html>

Note that we added a new line at scripts part, with some additional validation methods. This is a simple example that will only work with the addition of the Listing 4 .

Listing 4. New JavaScript code.

// A simple validation
$("#formComments").validate();


$("#formValidation").validate({
    debug: true,
    rules: {
        field1: {
            required: true,
            email: true,
        },
        field2: {
            minlength: 3,
            maxlength: 4,
            // or
            rangelength: [3, 4]
        },
        field3: {
            min: 10,
            max: 15,
            // or
            range: [10, 15]
        },
        field4: {
            accept: "audio/*"
        },
        personal_phone: {
            require_from_group: [1, ".phone_group"]
        },
        phone_home: {
            require_from_group: [1, ".phone_group"]
        },
        phone_work: {
            require_from_group: [1, ".phone_group"]
        }
    },
    messages: {
        field4: {
            accept: "Custom message: Provide a valid file type!"
        }
    }
});

This will be enough to see the result shown in Figure 2 .

Figure 2. Result of validate() method

Conclusion

Thus we reach the end of our article, where it was introduced concepts, the main features and how to use the Validation Plugin. So I hope that this plugin will be useful in your projects as proved in this article.

Thanks!



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login