bendrucker / ama

Ask me questions about building web applications
MIT License
6 stars 1 forks source link

Form validation practices #8

Closed owlyowl closed 9 years ago

owlyowl commented 9 years ago

Hi Ben, Just wondering out of interest how you were handling form validation in angular in general?

I was looking at patterns where you have validation directives on each input and just use css. A number of people seem to mention this book for validation practices: Mastering Web Application Development with AngularJS

Some people like Virgin America ended up having directives to create inputs and then form handlers which keep a record of each input directive and state.

They then end up passing in validator names and run the form through a validation regime for each named validator.

I'm currently researching decent approaches and was wondering in your travels a pattern you had found effective?

Everything from something a bit crazy like so: http://dotnetspeak.com/2013/11/validation-in-angular-forms-part-1 to a simpler stock approach like so: http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html

What I was thinking of doing was creating an input directive that would take things like min,max length, required, custom validation types and then create an input field which was still linked to the containing form.

I know virgin split their validation types by string and run them though validation some how but I can't work out if it extends or replaces the out of the box stuff

bendrucker commented 9 years ago

I'd like to help here but I need a more focused topic to give you a good answer. The short version is that I use ngMessages and add validation directives to each input.

owlyowl commented 9 years ago

Thanks Ben, You use something like so?

<input type="number" name="favoriteNumber"
       ng-model="profile.number"
       required min="1" /> 
<div ng-messages="profileForm.favoriteNumber.$error"   ng-messages-include="messages.html" class="errors"></div>
bendrucker commented 9 years ago

More or less. I tend to just include the errors inline versus an include.

owlyowl commented 9 years ago

Is there a way to determine which message is currently shown? I was thinking of doing some trickery to include the message inside the control and padding the inside of the control by the message length

bendrucker commented 9 years ago

Not clear on the question. ngMessages doesn't and should not expose an interface for which message is appearing. Why would you need to see that state?