6

The view model seems to be the most appropriate place to perform validation yet Angular seems to be pushing me down the popular form validation route.

Why Model Validation?

  • DRY - Applying validation to the model will centralize the validation logic as opposed to repeating it in every view.
  • Unit Testable - Since the logic isn't coupled in the HTML we are able to apply unit testing to our validation logic.
  • Shared Models - Shared view models can be validated regardless of what controller they interact with.

What I've looked into...

I've looked into creating a JSON schema to define a valid model with the following schema authority...

http://json-schema.org/

Whilst this is a viable option, I feel I am constraint to the schema and can therefore not apply custom validation or messages.

I feel like I need a mature validation library to handle this model validation but cannot find anything online to fit my needs.

How can you help?

I'm keen to know if other developers have had a similar experience and what their approach was. Have you found a viable model validation solution or have you stuck with form validation?

  • 7
    Validation is an area where it might be valuable to have it duplicated: Once on the client side to give fast feedback to your users and once on the server side to ensure the validation can't be bypassed. – Bart van Ingen Schenau May 26 '16 at 10:33
0

In angularJS, the correct way is to use directives to add validation constraint to a field.

Then you add those directives to the input/select/... in your form.

Using the ngModelController, you can set a different message for every type of errors.

To handle messages properly, i suggest you to check angular-message, it's a little utility library for errors message.

0

GUI validation can sometimes be a little more complicated then just checking what value the model has. For instance, has the user put focus on this field already or not? Should the fields that the user hasn't visited yet immediately have a red outline if it's required, or only after when the user attempted to save it or 'tabbed' past it?

The mixture of interaction does make the current way of specification in the view fair I think. There are plenty of hooks to customize around.

If you are specifying one validation for one field multiple times consider wrapping it in a directive. I have a hard time thinking of any occurrences where I allowed editing on one the same field in multiple views/forms though.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.