javascript 如何检查表单是否至少填写了一个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12077311/
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
How to check that a form has AT LEAST one field filled in
提问by Tom Perkins
I'm in the final stages of building a site and have one key task left: To setup some form validation that stops users being able to submit a blank search.
我正处于构建站点的最后阶段,还剩下一项关键任务:设置一些表单验证,阻止用户提交空白搜索。
I'm aware of the following post, but have found this unclear on how to get it to work, and how to use this for dropdown's (jQuery Validate - require at least one field in a group to be filled)
我知道下面的帖子,但我发现这不清楚如何让它工作,以及如何将它用于下拉列表(jQuery 验证 - 需要至少填充一个组中的一个字段)
Any ideas on how I can do this, or any pointers to a guide that may help, will be massively appreciated?
关于我如何做到这一点的任何想法,或任何可能有帮助的指南的指示,将不胜感激?
回答by Hymanwanders
Here is a function that should work with all form field types: text
, select
, radio
, checkbox
, textarea
, file
, and HTML5 input types like email
. The only assumption this function makes is that all select
elements have an option
with value=""
下面是应与所有表单字段类型工作的函数:text
,select
,radio
,checkbox
,textarea
,file
,和HTML5输入类型,如email
。该函数所做的唯一假设是所有select
元素都有一个option
withvalue=""
/**
* 1) gather all checkboxes and radio buttons
* 2) gather all inputs that are not checkboxes or radios, and are not buttons (submit/button/reset)
* 3) get only those checkboxes and radio buttons that are checked
* 4) get only those field elements that have a value (spaces get trimmed)
* 5) if the length of both resulting collections is zero, nothing has been filled out
*/
function checkFields(form) {
var checks_radios = form.find(':checkbox, :radio'),
inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]'),
checked = checks_radios.filter(':checked'),
filled = inputs.filter(function(){
return $.trim($(this).val()).length > 0;
});
if(checked.length + filled.length === 0) {
return false;
}
return true;
}
$(function(){
$('#myForm').on('submit',function(){
var oneFilled = checkFields($(this));
// oneFilled === true if at least one field has a value
});
});?
Here is a demo:
这是一个演示:
回答by Dorothy Kerrin Ryan
I'm not an expert, but this works for me. I have a select field and an input field for donations. If the amount isn't on the select options, then the user can add an amount into the input field. So at least one has to be submitted.
我不是专家,但这对我有用。我有一个选择字段和一个用于捐赠的输入字段。如果金额不在选择选项中,则用户可以在输入字段中添加金额。所以至少要提交一份。
function validateForm() {
if ( myform.mySelectfield.value == ""
&& myform.myInputfield2.value == ""
) {
alert( "Please enter at least field" );
return false;
}
}
//-->
And of course the input field needs to be numeric so I've added:
当然,输入字段需要是数字,所以我添加了:
function validateForm2() {
var x=document.forms["myform"]["myInputfield2"].value;
var x=document.forms["myform"]["myInputfield2"].value;
if (/[^0-9]+$/.test(x))
{
alert("Please enter a numerical amount without a decimal point");
myform.myInputfield2.focus();
return false;
}
}
}
The numerical check is called onkeyup:
数字检查称为 onkeyup:
onkeyup="validateForm2()"
I had to make a second function validateForm2(), because the numerical check didn't work in with the first one.
我不得不创建第二个函数validateForm2(),因为数字检查不适用于第一个。
回答by adeneo
//select all text inputs in form and filter them based on...
var isFilled = $('input[type="text"]', 'form').filter(function() {
return $.trim(this.value).length; //text inputs have a value
}).length; //get the selector length
//if selector contains at least one filled in text input, submit form
if (isFilled) {..submit form..}
回答by inhan
var filled = $('.property-list input[type="text"]').filter(function() {
var v = $(this).val();
// sanitize it first
v = v.replace(/[\s]{2,}/g,' ').replace(/^\s*(.*?)\s*$/,'');
$(this).val(v);
// if you want it to contain min.
// 3 consecutive alphanumeric chars, for example...
return /[a-z0-9]{3,}/i.test(v);
}).get();
if (filled.length) {
// do whatever with the result
alert('all okay');
} else {
$('.property-list input[type="text"]').focus().blur();
// this is for the placeholders to refresh, at least in Safari...
$('.property-list input[type="text"][value!=""]:first').focus();
var msg = 'plase fill at least one field with min. 3 ';
msg += 'consecutive alphanumeric characters';
alert(msg);
}