Вы находитесь на странице: 1из 8

(https://www.sitepoint.

com/)

OFFER ENDS IN 09 HRS 20 MINS 22 SECS


Start Learning For $9 (/Premium/L/Join?Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=Basic-Jquery-Form-Validation-
Tutorial&Ref_content=Javascript)

Javascript (Https://Www.Sitepoint.Com/Javascript/) > August 18, 2016


> By Julian Kühnel (https://www.sitepoint.com/author/jmotz/) By Sam Deering (https://www.sitepoint.com/author/sdeering/)

Basic jQuery Form Validation Example (2mins)

This popular article was updated on 18th August, 2016 to correct some minor errors and re ect the current version of the
library. Comments pertaining to the old article were deleted.

This tutorial shows you how to set up a basic form validation with jQuery, demonstrated by a registration form.

We’re going to use the jQuery Validation Plugin (https://jqueryvalidation.org/) to validate our form. The basic principle of this
plugin is to specify validation rules and error messages for HTML elements in JavaScript.

Here’s a live demo of what we’re going to be building:

EDIT ON
HTML SCSS JS Result

Registration
First Name
John
Last Name
Doe
Email
john@doe.com
Password
●●●●●

Register

This example is part of the article Basic jQuery Form Validation Example on
SitePoint by Julian Motz.

Step 1: Include jQuery


First, we need to include jQuery v1.x as the validation plugin is currently only compatible with jQuery versions lower than 2.0.

There are the following download options:

Download it from jquery.com (https://code.jquery.com/)


Download it using Bower: $ bower install jquery#1.x --save-dev
Download it using npm: $ npm install jquery@1.x --save-dev
Use a CDN: https://cdn.jsdelivr.net/jquery/1.12.4/jquery.min.js

Create a new HTML le named index.html and include jQuery before the closing </body> tag:

( )
(https://www.sitepoint.com/)
<!-- Change the "src" attribute according to your installation path -->
<script src="vendor/jquery/dist/jquery.min.js"></script>

OFFER ENDS IN 09 HRS 20 MINS 22 SECS


If you’d like toStart
use Bower or npm but aren’t familiar with them, you might be interested in these two articles:
Learning For $9 (/Premium/L/Join?Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=Basic-Jquery-Form-Validation-
Tutorial&Ref_content=Javascript)
Package Management for the Browser with Bower (https://www.sitepoint.com/package-management-for-the-browser-
with-bower/)
A Beginner’s Guide to npm — the Node Package Manager (https://www.sitepoint.com/beginners-guide-node-package-
manager/)

Step 2: Include the jQuery Validation Plugin


Choose between:

Download it from the plugin’s website (http://jqueryvalidation.org/ les/jquery-validation-1.15.0.zip)


Download it using Bower: $ bower install jquery-validation
Download it using npm: $ npm install jquery-validation
Use a CDN: https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js

Include the plugin after jQuery:

<!-- Change the "src" attribute according to your installation path -->
<script src="vendor/jquery-validation/dist/jquery.validate.min.js"></script>

Step 3: Create the HTML Form


For the registration we want to collect the following user information:

1 First name
2 Last name
3 Email
4 Password

So, let’s create our form containing these input elds:

<div class="container">
<h2>Registration</h2>
<form action="" name="registration">

<label for="firstname">First Name</label>


<input type="text" name="firstname" id="firstname" placeholder="John"/>

<label for="lastname">Last Name</label>


<input type="text" name="lastname" id="lastname" placeholder="Doe"/>

<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="john@doe.com"/>

<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;"/>

<button type="submit">Register</button>

</form>
</div>

( )
(https://www.sitepoint.com/)
When integrating this into a real application, don’t forget to ll in the action attribute, to make sure the form is submitted to
the correct destination.

09 HRS 20 MINS 22 SECS


Step 4: Create Styles for the Form
OFFER ENDS IN

Start Learning For $9 (/Premium/L/Join?Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=Basic-Jquery-Form-Validation-


Create a new le, css/styles.css, and includeTutorial&Ref_content=Javascript)
it in the <head> section of your HTML le:

<link rel="stylesheet" href="css/style.css"/>

Copy the following styles into the newly created le:

( )
(https://www.sitepoint.com/)
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Styles */
* {
OFFER ENDS IN 09 HRS 20 MINS 22 SECS
margin: 0;
Start Learning For $9 (/Premium/L/Join?Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=Basic-Jquery-Form-Validation-
padding: 0;
Tutorial&Ref_content=Javascript)
}

body {
font-family: "Open Sans";
font-size: 14px;
}

.container {
width: 500px;
margin: 25px auto;
}

form {
padding: 20px;
background: #2c3e50;
color: #fff;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
form label,
form input,
form button {
border: 0;
margin-bottom: 3px;
display: block;
width: 100%;
}
form input {
height: 25px;
line-height: 25px;
background: #fff;
color: #000;
padding: 0 6px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
form button {
height: 30px;
line-height: 30px;
background: #e67e22; 
color: #fff;
margin-top: 10px;
cursor: pointer;
}
form .error {
color: #ff0000;
}

If you’re using Compass (http://compass-style.org/) (SCSS) you can alternatively use the following to style the form:

( )
(https://www.sitepoint.com/)
@import "compass";
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Color settings */
OFFER ENDS IN 09 HRS 20 MINS 22 SECS
$formBg: #2c3e50;
Start Learning For $9 (/Premium/L/Join?Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=Basic-Jquery-Form-Validation-
$formColor: #fff;
Tutorial&Ref_content=Javascript)
$inputBg: #fff;
$inputColor: #000;
$buttonBg: #e67e22;
$buttonColor: #fff;
$errorMsgColor: #ff0000;

/* Styles */
* {
margin: 0;
padding: 0;
}

body {
font-family: "Open Sans";
font-size: 14px;
}

.container {
width: 500px;
margin: 25px auto;
}

form {
padding: 20px;
background: $formBg;
color: $formColor;
@include border-radius(4px);

label,
input,
button {
border: 0;
margin-bottom: 3px;
display: block;
width: 100%;
}
input {
height: 25px;
line-height: 25px;
background: $inputBg;
color: $inputColor;
padding: 0 6px;
@include box-sizing(border-box);
}
button {
height: 30px;
line-height: 30px;
background: $buttonBg;
color: $buttonColor;
margin-top: 10px;
cursor: pointer;
}
.error {
color: $errorMsgColor;
}
}

( )
(https://www.sitepoint.com/)
Note the styles for .error, which will be used for validation error messages.

Step 5: Create the Validation 09


Rules
HRS 20 MINS
OFFER ENDS IN 22 SECS
Finally, we need to initialize the form validation plugin. Create a new le js/form-validation.js and reference it after the
Start Learning For $9 (/Premium/L/Join?Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=Basic-Jquery-Form-Validation-
<script> tag of the jQuery Validation plugin: Tutorial&Ref_content=Javascript)

<script src="js/form-validation.js"></script>

Copy the following code into the newly created le:

// Wait for the DOM to be ready


$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname: "required",
lastname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});

Conclusion
That’s it, you’re done! Now you have an idea how to set up form validation with jQuery. Please keep in mind that this doesn’t
replace server-side validation. It’s still possible for a malicious user to manipulate or bypass the validation rules (e.g. using the
browser’s developer tools).

( )
(https://www.sitepoint.com/)
Related Articles
jQuery Ajax Validation Use the Remote Rule (https://www.sitepoint.com/jquery-ajax-validation-remote-rule/)
10 jQuery Form Validation Plugins OFFER ENDS IN 09 HRS 20 MINS 22 SECS
(https://www.sitepoint.com/10-jquery-form-validation-plugins/)

Start Learning For $9 (/Premium/L/Join?Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=Basic-Jquery-Form-Validation-


Tutorial&Ref_content=Javascript)
Meet the author
Julian Kühnel (https://www.sitepoint.com/author/jmotz/)  (http://codepen.io/julmot/) 
(https://github.com/julmot)

Julian is a passionate software developer currently focusing on frontend technologies and loves open source.

Meet the author

(http
Sam Deering (https://www.sitepoint.com/author/sdeering/)  (https://twitter.com/samdeering) 
(https://plus.google.com/104487173540464647216/)  (https://github.com/sdeering)

Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate
others.

Stuff We Do About Contact Legals


Premium (/premium/) Our Story (/about-us/) Contact Us (/contact-us/) Terms of Use (/legals/)

Versioning (/versioning/) Press Room (/press/) FAQ (https://sitepoint.zendesk.com/hc/en-us) Privacy Policy (/legals/#privacy)

Themes (/themes/) Write for Us (/write-for-us/)

Forums (/community/) Advertise (/advertise/)

References (/html-css/css/)

Connect

 (https://www.facebook.com/sitepoint)  (http://twitter.com/sitepointdotcom)  (/versioning/)  (https://www.sitepoint.com/feed/)


 (https://plus.google.com/+sitepoint)
© 2000 – 2018 SitePoint Pty. Ltd.

Вам также может понравиться