Let's be honest, form validation with JavaScript can be a real bitch. On a real basic level, however, it's not that bad. HTML5 has jumped in to some extent, providing a few attributes to allow us to mark fields as required or only valid if matching a given regular expression. What some people don't know is that you can style elements base on their required, valid, or invalid values. Here's how!
老实说,使用JavaScript进行表单验证确实是个real子。 但是,从实际的角度来看,还算不错。 HTML5在某种程度上已经加入,提供了一些属性,使我们可以将字段标记为必填字段,或者仅在匹配给定正则表达式时才有效。 某些人不知道的是,您可以根据元素的必需,有效或无效值设置样式。 这是如何做!
CSS (The CSS)
Each state is colon-separated from the element it's associated with:
每个状态均与与其关联的元素以冒号分隔:
/* basics */
input:required {
border: 1px solid blue;
}
input:valid {
border: 1px solid green;
}
input:invalid {
border: 1px solid red;
}
These pseudo classes are straight forward and useful. Here we're changing only borders, but you could use :before
and :after
to place text or an image next to each field, representing their state.
这些伪类非常简单和有用。 在这里,我们仅更改边框,但是您可以使用:before
和:after
在每个字段旁边放置文本或图像,以表示其状态。
Being able to style elements based on invalid or valid information is something we've shimmed forever with JavaScript, but now we can do so (to some degree) with pure CSS!
能够基于无效或有效信息设置元素样式是我们使用JavaScript永远无法实现的目标,但是现在我们可以(在某种程度上)使用纯CSS做到这一点!