使用jQuery简化表单验证

Wordpress5个月前发布 SUYEONE
610 0 0

In the previous tutorial, we discussed how to use certAIn input attributes and regular expressions for basic form validation in HTML5. In this tutorial, you’ll learn how to add simple form validation to your Website using jQuery plugins. Using jQuery plugins for form validation offers numerous advantages. They provide adDiTional functionality, such as easily displaying custom error messages and adding conditional logic to jQuery form validation. Validation libraries also allow you to add validation to HTML forms with minimal or no changes to the markup, and validity conditions can be easily added, rEMOved, or modified.

### Getting Started

For this tutorial, we’ll be using the jQuery Validation Plugin. This plugin provides many features and helps you define your own validation logic. Before we start using it in our projects, we need to include the necessary files. There are two main files to include:

1. The core file, which contains the plugin’s core functionality, including various validation methods and custom selectors.
2. An additional file with extra methods for validating credit card numbers and U.S. phone numbers.

You can add these files to your project using package managers like Bower or NPM. Alternatively, you can get the CDN links for the files and include them in `script` tags on your web page. Since this is a jQuery-based plugin, you’ll also need to add a link to the jQuery library.

“`html

“`

After including these files, you can start using the `validate()` method to validate any form.

### Validating Your First Form

You can begin using the plugin without making significant changes to your markup. The only modification you might need is to add an `id` or `class` (if not already present) to the form you want to validate.

Here’s a basic form that we’ll use the jQuery Validation Plugin to validate:

“`html

“`

We’ve used the same attributes as in the previous HTML5-based form validation tutorial. Even without JavaScript, the form will still be validated. However, using the plugin will result in error messages displayed right below invalid input fields, allowing us to style them as needed.

To start using the plugin for form validation, add the following JavaScript code to your webpage:

“`javascript
$(document).ready(function(){
$(‘#basic-form’).validate();
});
“`

Assuming you’ve already included the required JavaScript files, this code ensures the form is correctly validated and displays all error messages. Here’s a working demo.

The library only shows error messages when necessary, providing a smooth user experience. For instance, if you tab through the Name and Email fields without entering any information, no error messages will appear. However, if you enter just one character in the “Name” field and try to move to the “Email” field, an error message will prompt you to enter at least three characters.

### Options for the `validate()` Method

In the previous example, we called the `validate()` method without passing any options. However, you can also pass an object containing various options to this method. These values determine how the form plugin handles validation, errors, and more.

If you want the plugin to ignore certain elements during validation, you can easily do so by passing a class or selector to the `ignore()` method. When the plugin validates inputs, it ignores all form elements that match the specified selector.

### Adding Validation Rules to Input Fields

You can also pass validation rules to the `validate()` method to determine how input values should be validated. The `rules` parameter value should be an object with key-value pairs. Each key represents the name of the element you want to validate. The value is an object containing a set of rules for validation.

Using the `depends` keyword, you can add conditional logic to different fields being validated and pass a callback function that returns `true` or `false`. Here’s an example that defines validation rules for input fields:

“`javascript
$(document).ready(function(){
$(‘#basic-form’).validate({
rules: {
name: { required: true, minlength: 3 },
age: { required: true, number: true, min: 18 },
email: { required: true, email: true },
weight: {
required: depends: function(elem){
return $(‘#age’).val() > 50;
},
number: true,
min: 0
}
}
});
});
“`

In this code snippet, keywords like `name`, `age`, `email`, and `weight` correspond to the names of input elements. Each key has an object as its value, where the key-value pairs decide how the input field is validated.

These validation options resemble the attributes you can add to form markup. Setting `required` to `true` makes the element mandatory for form submission. Setting `minlength` to a value like `3` enforces a minimum of three characters in a text input. There are other built-in validation methods, briefly outlined in the plugin’s documentation.

One notable point here is that if you’re over 50 years old, the `weight` field becomes required, thanks to the `depends` condition that checks if the value entered in the `age` input field is greater than 50.

### Customizing Error Messages

This plugin allows you to set custom error messages for different validation rules in your form. First, set the `messages` key’s value to an object containing key-value pairs for input fields and their respective error messages.

Here’s an example that displays custom error messages for each input field:

“`javascript
messages: {
name: { minlength: “Name should have at least 3 characters” },
age: { required: “Enter your age.”, number: “Enter your age numerically”, min: “You must be at least 18 years old” },
email: { email: “Email format should be: abc@domain.tld” },
weight: { required: “People over 50 must enter their weight”, number: “Enter your weight numerically” }
}
“`

As with rules, the `messages` depend on the names of input fields. Each input field accepts an object with key-value pairs, where the key corresponds to the validation rule that should trigger the error message. If no custom error message is provided, the plugin will display a generic error message for the violated rule. Try filling in different values in the demo below to see custom and common error messages in Action.

### Customizing the Appearance of Error Messages

Sometimes, you might want to add your own classes to valid and invalid inputs for more precise targeting or better integration with your existing theme. You can use the `errorClass` and `validClass` keys to change the classes added to valid or invalid `input` elements. This helps prevent unnecessary conflicts due to reusing the same class names.

By default, the `errorClass` is assigned to each invalid input element and label, while the `validClass` is assigned to each valid input element. It’s important to note that setting `errorClass` to ‘fail-alert’ removes the error class from invalid elements. To assign multiple classes to the same element, use `errorClass: “error Failure-alert”` and `validClass: “valid Success-alert”`.

The only additional JavaScript code here is for assigning the classes:

“`javascript
$(document).ready(function(){
$(‘#basic-form’).validate({
errorClass: “error failure-alert”,
validClass: “valid success-alert”,
// … more validation code from the previous examples
});
});

// CSS to change the appearance of error messages and valid inputs:
label.error.fail-alert {
border: 2px solid red;
border-radius: 4px;
line-height: 1;
padding: 2px 0 6px 6px;
background: #ffe6eb;
}

input.valid.success-alert {
border: 2px solid #4CAF50;
color: green;
}
“`

In addition to customizing error messages, we also apply our own styles to valid input elements. Check out the CodePen demo below to see the final result.

### More Options to Alter Plugin Behavior

You can modify the plugin’s behavior by setting `onfocusout`, `onkeyup`, or `onclick` to `false`. Remember, `Boolean true` is not a valid value for these keys. Essentially, if you want the plugin to validate on keyup events or when focus is lost, just leave these options unchanged.

You can also choose to change the element that displays errors. By default, the plugin uses the `label` element to show all error messages, but you can use the `errorElement` option to change it to `em` or any other element. The `wrapper` key lets you wrap the error element in another HTML element.

These are some of the most commonly used options for validating forms. However, if you want to change the position of error messages or merge them, there are other validation options

© 版权声明

相关文章

暂无评论

暂无评论...
☺一键登录开启个人书签等功能!