jQuery 确保所有表单字段都已填写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18907198/
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 make sure all form fields are filled
提问by sf89
I have a simple form I'm making client side validation for. To validate, none of the fields should be left blank. This is how I go at it:
我有一个简单的表单,我正在为其进行客户端验证。要进行验证,不应将任何字段留空。这就是我的处理方式:
function validateForm() {
$('.form-field').each(function() {
if ( $(this).val() === '' ) {
return false
}
else {
return true;
}
});
}
For some reason, my function always returns false, even though all fields are filled.
出于某种原因,即使所有字段都已填充,我的函数始终返回 false。
回答by Guttsy
You cannot return false from within the anonymous function. In addition, if it did work, you would return false if your first field was empty, true if not, and completely ignore the rest of your fields. There may be a more elegant solution but you can do something like this:
您不能从匿名函数中返回 false。此外,如果它确实有效,如果您的第一个字段为空,则返回 false,否则返回 true,并完全忽略其余字段。可能有更优雅的解决方案,但您可以执行以下操作:
function validateForm() {
var isValid = true;
$('.form-field').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
return isValid;
}
Another recommendation: this requires you to decorate all of your form fields with that formfield class. You may be interested in filtering using a different selector, e.g. $('form.validated-form input[type="text"]')
另一个建议:这要求您使用该 formfield 类装饰所有表单字段。您可能对使用不同的选择器进行过滤感兴趣,例如$('form.validated-form input[type="text"]')
EDITAh, I got beat to the punch, but my explanation is still valid and hopefully helpful.
编辑啊,我被打败了,但我的解释仍然有效,希望能有所帮助。
回答by Arun P Johny
You were returning from the inner function not from the validate
method
你是从内部函数而不是validate
方法返回
Try
尝试
function validateForm() {
var valid = true;
$('.form-field').each(function () {
if ($(this).val() === '') {
valid = false;
return false;
}
});
return valid
}
回答by Irfan TahirKheli
function validateForm() {
var invalid= 0;
$('.form-field').each(function () {
if ($(this).val() == '') {
invalid++;
}
});
if(invalid>0)
return false;
else
return true;
}
回答by delagics
Here is a similar approach:
这是一个类似的方法:
function validateForm() {
var valid = true;
$('.form-field').each(function() {
valid &= !!$(this).val();
});
return valid;
}
!!
just converts input value to bool
!!
只是将输入值转换为 bool