zoukankan      html  css  js  c++  java
  • html5新增的客户端校验 Athena

    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>
  • 相关阅读:
    搭建vue项目脚手架
    vue项目中的iconfont图标下载及配置
    vue-awesome-swiper 轮播图的使用
    IDEA自动生成Mapper和实体文件
    云服务器通过IP如何访问项目
    社保,步入社会的第一步
    Memcached安装与启动
    IDEA提示非法字符,你不懂的UTF-8
    MyEclipse导入eclipse的web项目,将WebRoot切换为WebContent
    Myeclipse2017删除tomcat后,项目全部报错的解决办法
  • 原文地址:https://www.cnblogs.com/athean/p/6696452.html
Copyright © 2011-2022 走看看