Javascript Validation for all field with Required attribute

元气小坏坏 提交于 2019-12-04 02:33:51

In case that input[type=submit] is used, you don't need any 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>

Working jsBin

But if input[type=button] is used for submitting the form, use the snippet below

<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

this will be validating all your form field types

$('#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 
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!