Using only html
Recently, at work, I was creating a text input field and asked myself a question:
And lo and behold, there was!
The "pattern" attribute
Input tags with the type "text" have an attribute called
pattern which takes in regex as a string and creates validates the input against it.
So, let's say you want to make sure an input text field validates for basic semantic versioning, a.k.a
major.minor.patch, you would go:
<input type="text" pattern="(\d*)\.(\d*)\.(\d\*)"/>
And voila! Your text input has validation!
The Pros and Cons
- Less code, less to maintain.
- Faster to implement.
- Cannot handle complex validations that take more than some simple regex. For example, what if you wanted to validate against multiple patterns?
- Hard to write a test against, because the error field (a.k.a the "Please match the requested format") message is part of the native
- Cannot customize error messages.