jQuery 验证触发错误信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10350154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery validation trigger error message
提问by mannge
I have a kinda wierd problem. I want to trigger a jquery-valdation errormessage on an element even thou it's valid.
我有一个有点奇怪的问题。我想在元素上触发 jquery-valdation 错误消息,即使它是有效的。
Scenario: I have a large form. One of the inputs is for PersonalId. It's optional to enter that PersonalId. Beside that input i have a normal button (not the submit-button). If you click on that (fetching information from ajax) and the PersonalId field is empty i want to trigger that Error-message.
场景:我有一个大表格。输入之一是 PersonalId。输入该 PersonalId 是可选的。除了那个输入我有一个普通按钮(不是提交按钮)。如果您单击它(从 ajax 获取信息)并且 PersonalId 字段为空,我想触发该错误消息。
Is that possible with jQuery Validate or do i need to create my own function?
jQuery Validate 是否可以实现,或者我是否需要创建自己的函数?
回答by Andrew Whitaker
Is that possible with jQuery Validate or do i need to create my own function?
jQuery Validate 是否可以实现,或者我是否需要创建自己的函数?
Both, sort of. You can use the showErrors
function to display errors on the form manually, but since you don't want this to be a rule that is enabled when you submitthe form, you'll have to do your own checking for the value in the input.
两者,都差不多。您可以使用该showErrors
函数在表单上手动显示错误,但由于您不希望这是在提交表单时启用的规则,因此您必须自己检查输入中的值。
Something like:
就像是:
var $validator = $("#myform").validate();
$("#checkid").click(function() {
var errors;
if (!$("#personalid").val()) {
/* Build up errors object, name of input and error message: */
errors = { personalid: "Please enter an ID to check" };
/* Show errors on the form */
$validator.showErrors(errors);
}
});
Example:http://jsfiddle.net/andrewwhitaker/XjZer/
示例:http : //jsfiddle.net/andrewwhitaker/XjZer/
Note that the form will still submit if there is nothing in the personalid
field.
请注意,如果personalid
字段中没有任何内容,表单仍将提交。