如何在按钮单击时触发HTML5验证错误

时间:2016-04-30 21:50:07

标签: html html5 forms validation

我有一个表格,分3步完成。在前两个步骤中,验证错误没有显示,因为它们没有提交按钮。我如何在这里触发错误?

enter image description here

1 个答案:

答案 0 :(得分:-1)

所以这里的代码就是你的工作......

   <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){ //do this only after the whole thing is loaded, use this for more complex error handles...
    $('#form_').submit(function(data){ //this is triggered once you try to submit your data
    var Nerror = 0; //we declare the number of errors
        if($('#name_input').val()==''){  //here is where you handle errors, checking whether or not you 
            $('#name_input').addClass('has-error'); 
            $('#name_input').val('');
            Nerror++; //increment +1 to Nerror
            alert('no name');
        } 
        if($('#lname_input').val()==''){
            $('#lname_input').addClass('has-error');
            $('#lname_input').val('');
            Nerror++;
            alert('no last name');
        }
            if(Nerror>0){ //if Nerror is bigger then zero, we use the .preventDefault method to make sure the form is not submited
                data.preventDefault();
            }
    });

});
 </script>
<body>

  <form id='form_' action='your_next_step.php' method='post'>
        <input type='text' name='name' id='name_input' required>   <!-- if you wish to make the inputs required, just put "required" inside the tags... -->
        <input type='text' name='lastname' id='lname_input' required>
            <button type='submit'>Next</button>
    </form> 
</body>

我希望你现在可以做到,如果你有更复杂的处理程序,比如检查你的数据库是否有相同的条目,那么你需要创建一个php文件,为你做这个,然后以JSON或其他方式返回结果.... 祝你好运。