要处理jQuery Validate的验证失败事件,您可以使用invalid
事件。这个事件会在表单验证失败时被触发。您可以为这个事件绑定一个函数,该函数将在验证失败时执行。下面是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Validate Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
</head>
<body>
<!-- Your form goes here -->
</body>
</html>
<form>
元素中添加一些输入字段,并为它们设置name
属性。例如:<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Submit">
</form>
validate()
方法初始化验证插件。然后,使用on()
方法绑定invalid
事件。例如:$(document).ready(function() {
$('#myForm').validate({
rules: {
username: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
messages: {
username: {
required: "Please enter your username",
minlength: "Username must be at least 4 characters long"
},
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
}
}
});
$('#myForm').on('invalid', function(event) {
// Your custom error handling code goes here
console.log('Validation failed');
});
});
在上面的示例中,当表单验证失败时,控制台将输出"Validation failed"。您可以根据需要修改invalid
事件处理函数以执行其他操作,例如显示错误消息或禁用提交按钮。