jquery.validate 插件 - 如何在表单验证之前修剪值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1827483/
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.validate plugin - how to trim values before form validation
提问by Tom
I'm using the excellent jquery.validation pluginby J?rn Zaefferer and I was wondering whether there's a easy way to automatically trim form elements before they are validated?
我正在使用J?rn Zaefferer出色的jquery.validation 插件,我想知道是否有一种简单的方法可以在验证表单元素之前自动修剪它们?
The following is a cut down but working example of a form which validates a email address:
以下是验证电子邮件地址的表单的简化但有效的示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js"
type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$("#commentForm").validate({
rules: {
email: {
required: true,
email: true
}
}
});
});
</script>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
<label for="cemail">E-Mail:</label><input id="cemail" name="email"
class="required email" />
<input class="submit" type="submit" value="Submit"/>
</form>
</body>
</html>
The problem is that some users are getting confused because they accidently enter some whitespace in their email address, e.g. "[email protected] ". And the form won't submit and has a error message: "Please enter a valid email address.". Non-techy users don't know how to spot whitespace and may just quit the site rather than try to work out what they've done wrong.
问题是一些用户因为不小心在他们的电子邮件地址中输入了一些空格而感到困惑,例如“[email protected]”。并且表单不会提交并出现错误消息:“请输入有效的电子邮件地址。”。非技术用户不知道如何发现空白,可能只是退出站点而不是尝试找出他们做错了什么。
Anyway, I was hoping I could chain "jQuery.trim(value)
" before the validation so the
whitespace is removed and the validation error never occurs?
无论如何,我希望我可以jQuery.trim(value)
在验证之前链接“ ”,以便删除空格并且永远不会发生验证错误?
I could use addMethodto build my own email validation function. But I'm sure there's a more elegant solution?
我可以使用addMethod来构建我自己的电子邮件验证功能。但我确定有更优雅的解决方案吗?
回答by MDP
I did this with success.
我成功地做到了这一点。
Instead of:
代替:
Email: { required: true, email: true }
I did this:
我这样做了:
Email: {
required: {
depends:function(){
$(this).val($.trim($(this).val()));
return true;
}
},
email: true
}
回答by hwiechers
This code works for me. I haven't used it much so there may be bugs.
这段代码对我有用。我用的不多,可能有bug。
It wraps each method and trims the first element which is value.
它包装每个方法并修剪第一个元素,即值。
(function ($) {
$.each($.validator.methods, function (key, value) {
$.validator.methods[key] = function () {
if(arguments.length > 0) {
arguments[0] = $.trim(arguments[0]);
}
return value.apply(this, arguments);
};
});
} (jQuery));
if you're using select2 and validation at the same time, I recommend to put el.val($.trim(el.val()));
inside an IF like this: if(el.prop('type') != 'select-multiple'){el.val($.trim(el.val()));}
. That way, your jquery validation will behave as expected, and it will let you select multiple items.
如果你使用选择2和验证的同时,我建议把el.val($.trim(el.val()));
一个IF像这里面的:if(el.prop('type') != 'select-multiple'){el.val($.trim(el.val()));}
。这样,您的 jquery 验证将按预期运行,并且可以让您选择多个项目。
回答by tmorell
Since I want this behavior on all my forms by default I decided to modify the jquery.validate.js file. I applied the following change to onfocusout method:
由于默认情况下我希望在所有表单上都有这种行为,因此我决定修改 jquery.validate.js 文件。我对 onfocusout 方法应用了以下更改:
Original:
原来的:
onfocusout: function (element, event) {
if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
this.element(element);
}
}
To:
到:
onfocusout: function (element, event) {
if (element.tagName === "TEXTAREA" || (element.tagName === "INPUT" && element.type !== "password")) {
element.value = $.trim(element.value);
}
if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
this.element(element);
}
}
I do want to allow spaces at the begging and end of password.
我确实想在密码的开头和结尾处允许空格。
autoTrim could be added as a property to options.
autoTrim 可以作为属性添加到选项中。
回答by mark
I like the approach by xuser (https://stackoverflow.com/a/10406573/80002), however, I do not like messing with the plugin source code.
我喜欢 xuser ( https://stackoverflow.com/a/10406573/80002) 的方法,但是,我不喜欢弄乱插件源代码。
So, I suggest doing this instead:
所以,我建议这样做:
function injectTrim(handler) {
return function (element, event) {
if (element.tagName === "TEXTAREA" || (element.tagName === "INPUT"
&& element.type !== "password")) {
element.value = $.trim(element.value);
}
return handler.call(this, element, event);
};
}
$("form").validate({
onfocusout: injectTrim($.validator.defaults.onfocusout)
});
回答by jeremyzilar
When downloading validator.js, there is a file called additional-methods.js that contains the method "nowhitespace" and "lettersonly" that will strip out any white space in a field.
下载 validator.js 时,有一个名为 additional-methods.js 的文件,其中包含方法“nowhitespace”和“lettersonly”,它们将去除字段中的任何空白。
rules: {
user_name: {
required: true,
minlength: 3,
nowhitespace: true
}
}
回答by Tom
For reference, until I find a more elegant solution, I'm using addMethodas follows:
作为参考,在找到更优雅的解决方案之前,我使用addMethod如下:
// Extend email validation method so that it ignores whitespace
jQuery.validator.addMethod("emailButAllowTrailingWhitespace", function(value, element) {
return (this.optional(element) || jQuery.validator.methods.email.call(this, jQuery.trim(value), element));
}, "Please enter a valid email");
$().ready(function() {
$("#commentForm").validate({
rules: {
cemail: {
required: true,
emailButAllowTrailingWhitespace: true
}
}
});
});
Note: this doesn't actually strip the whitespace from the field, it only ignores it. So you need to ensure you perform trim
on the server-side before inserting in the DB.
注意:这实际上并没有从字段中去除空白,它只会忽略它。因此,您需要确保trim
在插入数据库之前在服务器端执行。
回答by sevencardz
Add a new jQuery validator method requiredNotBlank
. Then apply that function to your elements rather than the default required
function. This solution doesn't change the original validator source code, nor does it modify the default required
function, nor does it modify the element's value directly.
添加一个新的 jQuery 验证器方法requiredNotBlank
。然后将该函数应用于您的元素而不是默认required
函数。该方案既不改动原始验证器源码,也不修改默认required
函数,也不直接修改元素的值。
// jQuery Validator method for required not blank.
$.validator.addMethod('requiredNotBlank', function(value, element) {
return $.validator.methods.required.call(this, $.trim(value), element);
}, $.validator.messages.required);
// ...
$('#requiredNotBlankField').rules('add', 'requiredNotBlank');
回答by Craig Wohlfeil
Starting from jQuery Validation plugin version 1.15 a normalizer functionis supported. The normalizer can transform the value of an element before validation.
从 jQuery Validation 插件版本 1.15 开始,支持normalizer 函数。规范器可以在验证之前转换元素的值。
Note that the result of the normalizer is only used for validation. If you would like to update the value of the element you must do so explicitly.
请注意,规范化器的结果仅用于验证。如果您想更新元素的值,您必须明确这样做。
$("#form").validate({
rules: {
email: {
required: true,
email: true,
// Optionally disable validation on every key press
onkeyup: false,
normalizer: function(value) {
// Update the value of the element
this.value = $.trim(value);
// Use the trimmed value for validation
return this.value;
}
}
}
});
回答by RyanCodes
Pulled the regex from the jquery validator. Just override their email validation.
从 jquery 验证器中提取正则表达式。只需覆盖他们的电子邮件验证。
$.validator.addMethod("email", function(value, element) {
value = value.trim();
return this.optional(element) || /^((([a-z]|\d|[!#$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
}, "Please enter a valid email.");
回答by Psytronic
Could you not bind the trim to a blur event? Something like...
您不能将修剪绑定到模糊事件吗?就像是...
$("#cemail").blur(function(){ $(this).val(jQuery.trim($(this).val()); });