我做了一个<input type="text" placeholder="phone or email" required="required" />
,我只是想知道我是否可以这样做,以便它需要有效的电子邮件或号码?
答案 0 :(得分:8)
可以使用input
属性http://jsfiddle.net/887saeeg/在pattern
上实施纯HTML数据验证。与:valid
和:invalid
伪类相结合,可以仅使用表示技术来实现良好的错误检查功能。当然,需要现代浏览器。 (我在功能性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, 50%, 70%, 1) transparent;
border-width: 0 5px 5px 5px;
left: 15px;
top: -5px;
}
input {
outline: 0;
}
input:invalid + .error {
display: block;
}