Simple Form Validation in Mithril Js
Last time, I covered the basics of Mithril by creating a simple login page. In this post I will continue with form validation in a simple way.
I couldn’t find any good tutorial covering form validation, except a snippet from how-to-mithril. This is my only reference for now, and I don’t have much experience with Mithril, so this tutorial maybe not the best practice.
This time we only need to modify Login.js
file. If you want to improve reusability, you may want to create separated file for each component.
Input components
I will create separated component for each input, first is user name.
|
|
I create UserNameInput
component by defining a view
method. I also added error
property to store validation result, value
property to store input value, which I will bind to input value later.
The next two functions are pretty self-explanatory, validate
function checks input value, while isValid
returns validation result.
Here I implement one-way data binding from component state to view, so I can set the value of input field using UserNameInput.value
(ie: clear input data).
|
|
For data binding on the other direction, from view to state, I used oninput
event, so when user types something, it will trigger the validation.
|
|
That’s how two-way data binding works in Mithril. This is something I really like about Mithril, just need to do a simple value assignment and we got data binding done.
And this line:
|
|
will show the error if validation failed.
Password input is pretty much the same.
|
|
Form component
I’ve created all input, now I need a form to put them in.
|
|
LoginForm
has isValid
function, which runs when user clicks login button.
|
|
Here I pass 2 input components above to LoginForm
, and call isValid
function to validate our form in onclick
event.
Finally, add css for validation message.
|
|
Final
The validation above is pretty simple. It works but there are room for improvement:
- Create component for each type of validation to maximize reusability (required, length, etc)
- Format error message with parameter
And many other things. You can use this tutorial as a base for further development. Have fun with Mithril!