要處理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
事件處理函數以執行其他操作,例如顯示錯誤消息或禁用提交按鈕。