解决方法@H_404_4@
可以使用模式属性:
http://jsfiddle.net/887saeeg/对输入实现仅HTML数据验证.结合:有效和:无效伪类,可以仅使用表示技术来获得良好的错误检查功能.当然,需要现代浏览器. (我在功能性CSS系列丛书的最后一卷[亚马逊上提供]中详细介绍了仅限浏览器的验证).
HTML:
<form>
<input type = "text" placeholder = "Phone or Email" required pattern = "^([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3})|(\d{3}-\d{3}-\d{4})$"/>
<input type = "submit" value = "Send" />
</form>
编辑:使用CSS伪类的示例:http://jsfiddle.net/292pp5gk/.
HTML:
<form>
<label>
<input type = "text" placeholder = "Phone or Email" required pattern = "^([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3})|(\d{3}-\d{3}-\d{4})$"/>
<span class = "error">Please provide a valid telephone or email</span>
</label>
<input type = "submit" value = "Send" />
</form>
CSS:
label {
position: relative;
}
.error {
position: absolute;
white-space: nowrap;
bottom: -8px;
left: 0;
transform: translateY(100%);
display: none;
background-color: hsla(0,50%,70%,1);
padding: 5px 10px;
border-radius: 5px;
font: normal 12px/1 Sans-Serif;
}
.error:before {
content: "";
position: absolute;
border-style: solid;
border-color: transparent transparent hsla(0,1) transparent;
border-width: 0 5px 5px 5px;
left: 15px;
top: -5px;
}
input {
outline: 0;
}
input:invalid + .error {
display: block;
}
HTML:
<form> <input type = "text" placeholder = "Phone or Email" required pattern = "^([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3})|(\d{3}-\d{3}-\d{4})$"/> <input type = "submit" value = "Send" /> </form>
编辑:使用CSS伪类的示例:http://jsfiddle.net/292pp5gk/.
HTML:
<form> <label> <input type = "text" placeholder = "Phone or Email" required pattern = "^([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3})|(\d{3}-\d{3}-\d{4})$"/> <span class = "error">Please provide a valid telephone or email</span> </label> <input type = "submit" value = "Send" /> </form>
CSS:
label { position: relative; } .error { position: absolute; white-space: nowrap; bottom: -8px; left: 0; transform: translateY(100%); display: none; background-color: hsla(0,50%,70%,1); padding: 5px 10px; border-radius: 5px; font: normal 12px/1 Sans-Serif; } .error:before { content: ""; position: absolute; border-style: solid; border-color: transparent transparent hsla(0,1) transparent; border-width: 0 5px 5px 5px; left: 15px; top: -5px; } input { outline: 0; } input:invalid + .error { display: block; }