如何检查表单至少填写一个字段

我正处于构建网站的最后阶段,还剩下一个关键任务:设置一些表单validation,阻止用户提交空白搜索。

我知道以下post,但发现如何使其工作,以及如何将其用于下拉列表( jQueryvalidation – 要求填充组中的至少一个字段 )

关于我如何做到这一点的任何想法,或任何可能有用的指南指南都将受到大力赞赏?

这是一个应该适用于所有表单字段类型的函数: textselectradiocheckboxtextareafile和HTML5输入类型,如email 。 这个函数唯一的假设是所有select元素都有一个value=""option

 /** * 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 }); });​ 

这是一个演示:

— jsFiddle DEMO —

我不是专家,但这适合我。 我有一个选择字段和一个输入字段用于捐赠。 如果金额不在选择选项上,则用户可以在输入字段中添加金额。 所以至少要提交一个。

  function validateForm() { if ( myform.mySelectfield.value == "" && myform.myInputfield2.value == "" ) { alert( "Please enter at least field" ); return false; } } //--> 

当然输入字段需要是数字,所以我添加了:

  function validateForm2() { 

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; } 

}

数字检查称为onkeyup:

 onkeyup="validateForm2()" 

我不得不创建第二个函数validateForm2(),因为数字检查不适用于第一个函数。

 //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..} 
 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*$/,'$1'); $(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); }