Today I introduce you to jQuery Validade, an excellent jQuery plugin developed by the team at
http://bassistance.de.
You can download this plugin directly from the developer’s site (mentioned above) or from the
GitHub repository
(_https://github.com/jquery-validation/jquery-validation).
If you use GIT for version control, you can run the command below to clone the plugin’s
official repository:
1
| $ git clone https://github.com/jzaefferer/jquery-validation.git
|
To use this plugin you need to use jQuery.
Let’s get our hands dirty
Add the lines below inside the head tag of your
HTML document.
1
2
| <script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
|
Now let’s create a form and add some fields. Check it out below:
1
2
3
4
5
6
7
8
| <form id="formulario" action="" method="post">
Nome: <input type="text" name="nome" id="nome" /><br />
Email: <input type="text" name="email" id="email" /><br />
Senha: <input type="password" name="senha" id="senha" /><br />
Confirmação de Senha: <input type="password" name="confirmar_senha" id="confirmar_senha" /><br />
Termos de Contrato: <input type="checkbox" name="termos" id="termos"/><br />
<input type="submit" value="Cadastrar" />
</form>
|
Now we’ll validate the form we’ve just created, to do this add the following lines of code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| <script type="text/javascript">
$(document).ready(function(){
$('#formulario').validate({
rules: {
nome: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
senha: {
required: true
},
confirmar_senha: {
required: true,
equalTo: "#senha"
},
termos: "required"
},
messages: {
nome: {
required: "O campo nome é obrigatório.",
minlength: "O campo nome deve conter no mínimo 3 caracteres."
},
email: {
required: "O campo email é obrigatório.",
email: "O campo email deve conter um email válido."
},
senha: {
required: "O campo senha é obrigatório."
},
confirmar_senha: {
required: "O campo confirmação de senha é obrigatório.",
equalTo: "O campo confirmação de senha deve ser identico ao campo senha."
},
termos: "Para se cadastrar você deve aceitar os termos de contrato."
}
});
});
</script>
|
Now just run your HTML document in your
browser to see the final result.
I hope you liked it, if you have questions about using the plugin, leave a comment.