表单验证可以通过两种方式:AJAX 与 html5表单验证。
下面简单介绍基本的 h5 表单验证特性:
html5 设置表单元素必填 --> required
html5 表单验证使用正则 --> pattern
html5 表单中设置了必填,提交表单的时候如何做到不验证 --> novalidate 或者 formnovalidate
示例一:
<body>
<input type="text" name="text" placeholder="请输入时间" onfocus="(this.type='date')">
<form action="" method="post" enctype="multipart/form-data" novalidate>
<!-- anction 为后台交互的提交地址 -->
<input type="file" name="file">
<!-- 有file type 的input 那么form 里面要加上如上的enctype 属性 -->
<label>用户名</label>
<input type="text" name="user" placeholder="请输入用户名" required autofocus />
<input type="submit" name="submit" />
</form>
<form action="" method="post" enctype="multipart/form-data">
<!-- anction 为后台交互的提交地址 -->
<input type="file" name="file">
<!-- 有file type 的input 那么form 里面要加上如上的enctype 属性 -->
<label>用户名</label>
<input type="text" name="user" placeholder="请输入用户名" required autofocus />
<input type="submit" name="novasubmit" formnovalidate />
<input type="submit" name="submit" />
</form>
</body>
示例二:
<form action="" method="post" enctype="multipart/form-data" autocomplete="on">
<!-- anction 为后台交互的提交地址 -->
<input type="file" name="file">
<!-- 有file type 的input 那么form 里面要加上如上的enctype 属性 -->
<label>用户名</label>
<input type="text" name="user" placeholder="请输入用户名" required autofocus />
<label>id</label>
<input type="text" name="idname" placeholder="请输入ID" pattern="^\d{5}[a-z]$" />
<input type="text" list="tips">
<datalist id="tips">
<option value="erwer">1</option>
<option value="erwer2">2</option>
</datalist>
<input type="submit" name="submit" />
</form>
其中,label for属性的用法,用于radio 与checkbox,点击label 相应的会选中选项,示例
<label for="man"></label>
<input type="radio" name="sex" id="man">
<label for="woman"></label>
<input type="radio" name="sex" id="woman">