HTML5

HTML5之表单验证

2019-04-10  本文已影响0人  Leophen
例1:去除表单在chrome浏览器中记住密码后自动填充的黄色背景
before.jpg
after.jpg

(使用-webkit-autofill控制css样式来实现)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        input:-webkit-autofill{
                -webkit-box-shadow:0 0 0 10px #fff inset;
            }
    </style>
</head>

<body>
    <input type="text" Name="username">
</body>

</html>
<input type="radio" id="man">
<label for="man">男</label>
HTML5约束验证API
  1. validity 属性(true则为该项有问题)
  • patternMismatch对应pattern属性,规定用于验证表单元素的值的正则表达式。
  • valueMissing对应required设置表单必填 。
  • stepMismatch对应step属性,规定表单元素的合法数字间隔。
  • tooLong对应maxlength属性,规定文本区域的最大长度(以字符计)
  • tooShort相反,二者恒等于false
  • rangeOverflow对应的是最大值max
  • rangeUnderflow对应的是最小值min
  1. willValidate 属性:表示如果元素的约束没有被符合则值为 false
  2. validationMessage 属性:用于描述与元素相关约束的失败信息
  3. checkValidity()方法:表示如果元素没有满足它的任意约束,返回false,其他情况返回 true
  4. setCustomValidity() 方法:设置自定义验证信息
例2:去除表单number表单后面的选择按钮
before.jpg
after.jpg
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title></title>
    <style type="text/css">
    input[type="number"]::-webkit-inner-spin-button,
    input[type="number"]::-webkit-outer-spin-button {
        -webkit-appearance: none;
    }
    </style>
</head>

<body>
    <input type="number" value="">
</body>

</html>

(当输入类型为type="number"时,要保留2位小数,可以设置step="0.01",这样提交的数字就会保留2位小数)

例3:用setCustomValidity()修改默认提示
before.jpg
after.jpg
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title></title>
</head>

<body>
    <form action="" method="get">
        <input type="url" oninput="checkit(this)">
        <input type="submit" value="提交">
    </form>
    <script>
    function checkit(obj) {
        var it = obj.validity;
        if (true === it.typeMismatch) {
            obj.setCustomValidity("请输入带http://的正确地址!");
        } else {
            obj.setCustomValidity("输入正确!");
        }
    }
    </script>
</body>

</html>
HTML5自带验证伪类和选择器
+.jpg

(后面的label,可以用+选择器,也可以用~选择器,都能选取到)

例4:用invalid和valid实现表单实时检测
invalid和valid.gif
//invalid和valid实现样式
input:valid ~label::after{
  content: "你输入正确!"
}
input:invalid ~label::after{
  content: "你邮箱错误!"
}
//表单内容
<input id="mail" type="email" required placeholder="输入邮箱">
<label for="mail"></label>
触发事件
例5:oninvalid实现自定义表单提示
oninvalid-oninput-onchange.gif
//表单内容
<div class="onelist">
  <label for="UserName">手机号</label>
  <input name="UserName" id="UserName" type="text" placeholder="请输入手机号码" pattern="^1[0-9]{10}$" required oninvalid="this.setCustomValidity('请输入正确的号码');" oninput="setCustomValidity('')">
</div>

<div class="onelist">
  <label for="Password">密码</label>
  <input name="Password" id="Password" type="password" placeholder="6~20位" class="" pattern="^[a-zA-Z0-9]\w{5,19}$" required oninvalid="this.setCustomValidity('请输入正确密码');" oninput="setCustomValidity('')" onchange="checkPassword()">
</div>

<div class="onelist">
  <label for="Repassword">确认密码</label>
  <input name="Repassword" id="Repassword" type="password" placeholder="确认密码" class="" required onchange="checkPassword()">
</div>

<div class="onelist">
  <input type="submit" value="提交">
</div>

//检测两次密码是否一致
<script type="text/javascript">
function checkPassword() {
  var pass1 = document.getElementById("Password");
  var pass2 = document.getElementById("Repassword");

  if (pass1.value != pass2.value)
    pass2.setCustomValidity("两次输入的密码不匹配");
  else
    pass2.setCustomValidity("");
}
</script>
表单提示信息的插入
例6:阻止表单气泡并显示提示信息
气泡自定义.gif
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <title>表单验证默认样式修改</title>
</head>
<style>
    .oneline{line-height: 1.5;margin:10px auto;}
    .oneline label{width:100px;text-indent: 15px;font-size:14px;font-family: "Microsoft Yahei";display: inline-block;}
    .oneline .sinput{width:60%;height:30px;border-radius: 6px;border:1px solid #e2e2e2;}
    .oneline input[type="submit"]{margin-left:20px;width:80px;height:30px;border:0;background-color:#5899d0;color:#fff;font-size:14px;border-radius: 6px;}
    .error-message{color:red; font-size:12px;text-indent:108px;}
</style>

<body>
    <form id="forms">
        <div class="oneline">
            <label for="name">用户名:</label>
            <input id="name" name="name" class="sinput" required>
        </div>
        <div class="oneline">
            <label for="email">Email:</label>
            <input id="email" name="email" class="sinput" type="email" required>
        </div>
        <div class="oneline">
            <input type="submit" value="提交" id="thesubmit">
        </div>
    </form>
    <script>
    function replaceValidationUI(form) {

        form.addEventListener("invalid", function(event) {
            event.preventDefault();
        }, true);

        form.addEventListener("submit", function(event) {
            if (!this.checkValidity()) {
                event.preventDefault();
            }
        }, true);
        var submitButton = document.getElementById("thesubmit");
        submitButton.addEventListener("click", function(event) {
            var inValidityField = form.querySelectorAll(":invalid"),
                errorMessage = form.querySelectorAll(".error-message"),
                parent;

            for (var i = 0; i < errorMessage.length; i++) {
                errorMessage[i].parentNode.removeChild(errorMessage[i]);
            }
            for (var i = 0; i < inValidityField.length; i++) {
                parent = inValidityField[i].parentNode;
                parent.insertAdjacentHTML("beforeend", "<div class='error-message'>" + inValidityField[i].validationMessage + "</div>")
            }
            if (inValidityField.length > 0) {
                inValidityField[0].focus();
            }
        })
    }
    var form = document.getElementById("forms");
    replaceValidationUI(form);
    </script>
</body>

</html>
上一篇下一篇

猜你喜欢

热点阅读