An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
Form input validation WITHOUT JavaScript
I promised it and here it is,
BEHOLD!
Quick Explanation
We need 2 things here:
Pattern
The pattern attribute allows us to specify a regular expression that the inputted value must match in order to be considered valid.
:valid, :invalid
When used in an input, CSS considers it :valid when the regex set in the pattern attribute matches the user input on it. Otherwise it's considered :invalid.
Basic Usage
html
<form> <label for="choose">Would you prefer tea or coffee?</label> <input id="choose" name="i_like" required pattern="[Tt]ea|[Cc]offee"> <button>Submit</button></form>
css
input:valid { color: green }input:invalid { color: red }
ending
If you try to submit (thats why I left that button in the codepen) while any input in the form is not valid, it will show you a message in YOUR language. Without the need of i18n or anything else, the browser will handle that for you.
I feel this a nice approach for UX; whenever you need to give a quick feedback to the user.
You can design it your way and extend your creativity adding other CSS pseudos like:
And last but not least, you can also edit the label or another element by using the adjacent sibling selector +
, which is the reason I've set the label after the input in my codepen, check the CSS!
Also bookmark this for reference whenever you need it:
Till the next one!
Original Link: https://dev.to/joelbonetr/form-input-validation-without-javascript-1m53
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To