Javascript验证所有字段的Required属性

Javascript Validation for all field with Required attribute

本文关键字:Required 属性 字段 验证 Javascript      更新时间:2023-09-26

我到处寻找这个问题的答案,但是到处都找不到。

我有一个表单,它有HTML 'required'属性,它做了一个很好的突出显示提交前需要填写的字段…但是我的表单所依附的系统(我无法控制它)在几秒钟后还是提交了表单。它的提交依赖于Javascript。因此,我想写一个Javascript脚本来检查所需属性的所有字段。目前,我有一个脚本,指定字段,我想是强制性的,但如果它可以查找属性代替,那将是辉煌的。

如果使用input[type=submit],则不需要任何JavaScript

<form id="theForm" method="post" acion="">
  <input type="firstname" value="" required />
  <input type="lastname" value="" required />
  <input type="submit" name="submit" value="Submit" />  
</form>
工作jsBin

但是如果使用input[type=button]提交表单,则使用下面的代码片段

<form id="theForm" method="post" acion="">
  <input type="firstname" value="" required />
  <input type="lastname" value="" required />
  <input type="button" name="button" value="Submit" />  
</form>
window.onload = function () {
  var form = document.getElementById('theForm');
  form.button.onclick = function (){
    for(var i=0; i < form.elements.length; i++){
      if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
        alert('There are some required fields!');
        return false;
      }
    }
    form.submit();
  }; 
};

Wotking jsBin

多年以后,这里有一个使用更现代的Javascript的解决方案:

for (const el of document.getElementById('form').querySelectorAll("[required]")) {
  if (!el.reportValidity()) {
    return;
  }
}

请参阅Vlad的注释,以获得约束验证API的链接(感谢Vlad,这有帮助!)

我迟到了,但这对我很有用。

<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
    //success code here
    return true;
}

感谢Vlad和a.l.e用他们之前的答案为我指出了正确的方向。这是他们方法的简化版本。

您可以使用约束验证API,大多数浏览器都支持。

这将验证所有表单字段类型

$('#submitbutton').click(function (e) {
    e.preventDefault();
    var form = document.getElementById("myForm");
    var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
    var selects = form.getElementsByTagName("select");
    for(var i = 0, len = inputs.length; i < len; i++) {
        input = inputs[i];
        if(input.type == "hidden") {
            continue;
        }
        if(input.type == "radio" && !input.checked) {
            not_pass = true;
        } 
        if(input.type == "radio" && input.checked){
            not_pass = false;
            break;
        }
        if(input.type == "text" && !input.value) {
            not_pass = true;
        } 
        if(input.type == "text" && input.value){
            not_pass = false;
            break;
        }
        if(input.type == "number" && !input.value) {
            not_pass = true;
        } 
        if(input.type == "number" && input.value){
            not_pass = false;
            break;
        }
        if(input.type == "email" && !input.value) {
            not_pass = true;
        } 
        if(input.type == "email" && input.value){
            not_pass = false;
            break;
        }
        if(input.type == "checkbox" && !input.checked) {
            not_pass = true;
        } 
        if(input.type == "checkbox" && input.checked) {
            not_pass = false;
            break;
        }
    }
    for(var i = 0, len = selects.length; i < len; i++) {
        select = selects[i];
        if(!select.value) {
            not_pass = true;
            break;
        } 
    }
    if (not_pass) {
        $("#req-message").show();//this div # in your form
        return false;
    } else {
     //do something here 
    }
});

如果使用"required"上述解决方案或"约束验证api";解决方案,如果选择选项取决于具有特定答案的另一个选择字段,则如何使其成为必需选项。我用了"要求"方法,如下图所示,它对国家选择非常有效。

<select  id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>
<script>
    $("select[name='country_code']").change(function() {
      if ($(this).val() == "US") {
        $("select[name='state_code'] option").removeClass('hidden');
        $("select[name='state_code'] option").addClass('required');
      } else {
      } else {
        $("select[name='state_code'] option").addClass('hidden');
      }
    });
</script> 
<label for="state_code">State/Province</label>
<select  id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>

可以看到,我尝试添加类"required"to State select if Country select is US,但它什么也没做。