html5新增的客户端校验

1.表单控件提供的checkValidity()方法进行校验。

例如:如果checkValidity()方法返回true
则表明该表单内的所有表单控件都有效。

<body>
    <form action="">
        生日:<input id="birth" name="birth" type="date"><br> 邮件地址:
        <input type="email" id="email" name="email"><br>
        <input type="submit" value="提交" onclick="return check()">
</form>
<script>
    var check = function () {
        return commonCheck('birth', '生日', '字段必须是有效的日期')
            && commonCheck('email', '邮箱', '字段必须符合电子邮件的格式')
    }
    var commonCheck = function (fieid, fieName, tip) {
        var targetEle = document.getElementById(fieid);
        if (targetEle.value.trim() == '') {
            alert(fieName + '字段必须填写');
            return false
        }
        else if (!targetEle.checkValidity()) {
            alert(fieName + tip);
            return false
        }
        return true
    }
</script>

</body>

2.自定义验证  应用h5新增的setCustomValidity()方法实现。只有当该表单没有通过校验时才能调用该方法。

例如:

<body>
    <form action="">
       图书名:<input id="name" name="name" type="text" required><br> 
        图书ISBN:<input type="text" id="isbn" name="isbn" required pattern="\d{3}-\d-\d{3}-\d{5}"
        ><br>
           图书价格:<input type="number" id="price" name="price" required min="20" max="150" step="5"
        ><br>
        <input type="submit" value="提交" onclick="check()">
</form>
<script>
    var check = function () {
      if(!document.getElementById('name').checkValidity()){
document.getElementById('name').setCustomValidity('图书名是必须的');
      }
            if(!document.getElementById('isbn').checkValidity()){
document.getElementById('isbn').setCustomValidity('图书isbn是必须的'+'\n而且必须符合xxx-x-xxx-xxxxx的格式(其中x代表数字)');

      }
            if(!document.getElementById('price').checkValidity()){
document.getElementById('price').setCustomValidity('价格是必须的'+'\n而且必须在20-150之间,且是5的倍数');
      }
    }
    
</script>

 

posted @ 2017-04-11 21:24  Athena-web  阅读(335)  评论(1编辑  收藏  举报