Custom Validation in Materialize css
Pulkit Kashyap
Posted on June 19, 2020
Hey! Thanks for dropping by. Well, if you are using Materialize in your project then I believe this trick can be really helpful for you. Almost every website has some kind of form or input fields the user interacts with. And most of the fields have some validation logic attached to them. Think of a case where you want the user to enter a unique username as the input. But when this username is not unique we immediately notify the user by displaying a warning for the same.
I had a similar use case and I was using Materialize, a CSS framework in my project. It provides you an easy way to show or customize warning messages if the input value is not in the expected format. But what if you want to perform custom validation for an input. For eg. username must not contain characters like @, { etc. Unfortunately the documentation does not mention any such scenarios.
So just like any other developer I googled that immediately. But I could not find any useful resource. After digging a bit on how Materialize manages to show the warning messages, I came out with a solution(a little hackish 😅). Basically Materialize adds valid class to the input to show succes message and vice-versa. Accordingly it displays the helper text. Here is a quick demo -
The above code checks if username contains [@.;:] and shows message accordingly. I attached event listeners for fetching the current value and toggled classes accordingly.
Hope this helped.
Find me on my social media handles 🤟.
Posted on June 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.