vendredi 3 avril 2015

form validation in react

I was wondering how people handle form validation. Currently I have inputs that have "isValid()" method on them and in the form component, I have to call



if(this.refs.username.isValid()
&& this.refs.firstName.isValid()
&& this.refs.lastName.isValid()
&& this.refs.email.isValid()
&& this.refs.password.isValid()
)


and that's just the beginning of the boilerplate. If I could iterate through this.props.children and call isValid on them that would go a long way but I can't seem to make that work.


I also can't seem to iterate through this.refs and do it dynamically like that either. I think. Pretty sure I tried that.


But basically if I can't interrogate my component's children and call methods on them then there is going to be a ton of boiler plate code in my/everyone's app.


Has anyone dealt with this yet?


Thanks,


r


EDIT - some code to demonstrate what I've tried



React.Children.map(this.props.children, function (
var valid = child.isValid();
});


Here child has props, ref, and type. This is helpful in general but not in my situation. I want to have access to the actual instance so I can call an is valid function on it.


EDIT again


I appreciate the pointer to another answer, however, I don't feel it is a similar question. I'm not asking HOW to validate, I'm asking whether anyone has found any good ways to wrap up validation. The answer given in the other post is basically just like my example above, very verbose and repetitive, they only show one field on a form so it doesn't look too bad but trust me after a couple of forms you are going to want to kill yourself.


So to clarify, I'm asking, given the repetitive nature of asking every child component if they are in a valid state, and if not, what error do they have and then aggregating that information, is there a better way. Perhaps if you could dynamically iterate through the children you could wrap the functionality up, but I have not been able to do that.


EDIT again


Here is a repo where I was messing with this stuff.


http://ift.tt/1C9BM5C


It's basically an editable display form or whatever. You go to the page and can view the data but if you want to edit it click the button. Edit the form and submit. That's just what I was playing with, it could just as easily be a "RHForm" that is used for all regular forms.


it's pretty simple the RHInput validates on change and also has an IsValid() method. Currently the app.jsx has to call isValid() on all it's children. If you look at RHEditableForm you'll see that this would be a perfect place to dynamically call IsValid() on whatever happens to be in there. This could be reused by all forms and I'd never/rarely have to write validation logic. Also since this is where the "OK" button is it also seems like the correct place to put validation.


Aucun commentaire:

Enregistrer un commentaire