DEV Community

HTML5 form validation in React

Arpy Vanyan on February 18, 2018

“Colorful lines of code on a computer screen” by Sai Kiran Anagani on Unsplash Best data is a validated data Users… Data collection… Forms… I’m...
Collapse
 
cuginoale profile image
Alessio Carnevale

Very nice article!
I am with you when it comes to form validation! I do think tho that the logic in the validate function can be simplified.
I am exploring a very similar approach here: dev.to/cuginoale/form-validationsu...

Your feedback would be highly appreciated! :)

Collapse
 
shelaghlewins profile image
Shelagh-Lewins • Edited

Thank you for the excellent article. It's a really nice reusable validated form component.

I have a couple of comments on the code in your CodePen based on my experience building this component.

I think the regular expression doesn't need to specify the length? The minLength attribute covers this and gives a more useful error.

When passing a regex in to a React component, you may need to modify it slightly (see stackoverflow.com/questions/444979...). I replaced

"(?=.*\d)(?=.*[a-z]).{6,}"

with

"^(?=.*\d)(?=.*[a-z]).+$"

In the Form component, I replaced

render() {
    const props = [...this.props];

with

render() {
    const props = { ...this.props };

because it generated an error. I think the original code was trying to cast an object to an array?

Collapse
 
skptricks profile image
skptricks

Thank you so much for this great article, I have found similar article :
skptricks.com/2018/06/simple-form-...

Collapse
 
_arpy profile image
Arpy Vanyan

Hi! Thanks for sharing. That's a nice article, but there is a huge difference her :) The article is about a single case of validating a user registration form with a custom validation check. While I suggest a common form component that can be used for all types of forms regardless of the inputs and the validation is done with the already existing and awesome HTML5 input validation ;)

Collapse
 
jgentes profile image
James Gentes

Nice article.. readers should know you need this babel plugin to make it work: babeljs.io/docs/en/next/babel-plug...