Home >Web Front-end >JS Tutorial >How to use jquery validate custom validation
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.
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>
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>
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(); });
4. Optional: Customize the verification error message.
$(document).ready(function () { // 自定义错误提示信息 $.extend($.validator.messages, { required: "该字段不能为空", customNumber: "请输入有效的数字" }); // 初始化validate插件 $("#myForm").validate(); });
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!