mdn拾遗-- 纯html+css实现的input的验证

关于input的验证,其实从很古老的前端时代开始就一直采用一种比较可靠的方式,就是js操作dom,今天浏览mdn时发现了h5的验证方法,很是兴奋。感觉值得一记。

  说在前面的话,着重就是配合h5 + css选择器的配合啦,废话不多说,上代码

  1.验证某个input为必填

          html:

<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input type="text" id="uname" name="name" required>
    <span class="validity"></span>
  </div>
  <div>
    <button>Submit</button>
  </div></form>

        css:

    div {
        margin-bottom: 10px;
        position: relative;
    }
        input + span {
            padding-right: 30px;
        }
        input:invalid+span:after {
            position: absolute;
            content: 'x';
            padding-left: 5px;
            color:red;
        }
        input:valid+span:after {
            position: absolute;
            content: '✓';
            padding-left: 5px;
            color:green;
        }

2.输入框的长度限制:就是minlength和maxlength的使用啦。

  html:

<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input type="text" id="uname" name="name" required size="10"
           placeholder="Username"
           minlength="4" maxlength="8">
    <span class="validity"></span>
  </div>
  <div>
    <button>Submit</button>
  </div></form>

3.使用pattern属性使用正则表达式:

  html:

<input type="text" id="uname" name="name" required size="45"
           pattern="[a-z]{4,8}">

写在最后,以前是自己对h5属性,以及一些css的东西不够重视,所以觉得能用js解决的就用js解决,但是现在看来不是了。h5确实是个伟大的东西,给web开发带来了视频,音频,canvas这些极度能够丰富网页内容的东西。值得学习啊。

posted @ 2018-09-13 10:09  子龙_子龙  阅读(19)  评论(0编辑  收藏  举报