Home > Web Front-end > JS Tutorial > How to use jquery validate custom validation

How to use jquery validate custom validation

DDD
Release: 2023-06-25 17:33:46
Original
1735 people have browsed it

jquery validate Custom validation steps: 1. Introduce the jQuery library and jQuery validate plug-in library; 2. Write HTML form code and add classes and custom validation rules for the fields that need to be validated; 3. In JavaScript Initialize the validate plug-in and add a custom validation method; 4.

How to use jquery validate custom validation

The steps to use jQuery validate to customize validation are as follows:

1. Introduce jQuery library and jQuery validate plug-in library.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
Copy after login

2. Write HTML form code and add classes and custom validation rules for the fields that need to be validated.

<form id="myForm">
<input type="text" name="username" class="required">
<input type="text" name="age" class="required customNumber">
<input type="submit" value="Submit">
</form>
Copy after login

3. Initialize the validate plug-in in JavaScript and add a custom verification method.

$(document).ready(function () {
// 验证规则
$.validator.addMethod("customNumber", function (value, element) {
return /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/.test(value);
}, "请输入有效的数字");
// 初始化validate插件
$("#myForm").validate();
});
Copy after login

4. Optional: Customize the verification error message.

$(document).ready(function () {
// 自定义错误提示信息
$.extend($.validator.messages, {
required: "该字段不能为空",
customNumber: "请输入有效的数字"
});
// 初始化validate插件
$("#myForm").validate();
});
Copy after login

Now, when the user submits the form, jQuery validate will automatically verify whether each field complies with the rules and display the corresponding error message. The custom verification method will verify according to the custom verification rules and display the custom error message

The above is the detailed content of How to use jquery validate custom validation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template