HomePortfolioBlogs

Do you know how to validate text inputs without javascript?

Using only html

Recently, at work, I was creating a text input field and asked myself a question:

"People must validate text inputs all the time. I wonder if there's another way to do it rather than using javascript to grab the input's value..."

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: pattern="(\d).(\d).(\d*)"

<input type="text" pattern="(\d*)\.(\d*)\.(\d\*)"/>

And voila! Your text input has validation!

Text Input Pattern

The Pros and Cons

PROS

  • Less code, less to maintain.
  • Doesn't require javascript.
  • Faster to implement.

CONS

  • 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 input tag.
  • Cannot customize error messages.

Conclusion

The pattern is great for input text validations that require simplicity and development speed. For anything else that's more complex, it's probably better to use the power of javascript.


Thanks for reading through! 🚀

If you're interested in seeing more of my blogs, please sign up below:

Sign Up For More Blogs

But first... are you a human?

Yes

No

© 2022, Ashcodes