HTML5 Required input styling

前端 未结 7 1236
眼角桃花
眼角桃花 2020-11-30 11:13

In HTML 5, we can mark inputs as required and then select them with the [required] pseudo-selector in CSS. But I only want to style them when they

相关标签:
7条回答
  • 2020-11-30 11:47

    You can use :valid and :invalid selectors. Something like this

    .field:valid {
        border-color:#0f0;
    }
    .field:invalid {
        border-color:#f00;
    }
    

    However, this will only work in browsers that support native validation, and only for fields that make sense. As far as I know, right now that only means Chrome (maybe Safari, but haven't checked).

    So by native validation I mean that in chrome if you do <input type="email"> the field's value will be validated for email type string (without any additional javascript), so the styles above will work. However, if you were to attach them to a type="text" field, or a second password field (that is suppose to match the first), you'd only ever get green because everything is valid, and in the case of password, there's no "type" for that anyway.

    Which basically means that to support all browsers, and more importantly, wider array of validations you still have to resort to javascript, in which case assigning .valid/.invalid class shouldn't be a problem. :)

    0 讨论(0)
提交回复
热议问题