Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular with .NET WebAPI validation, and single-point-of-truth

Is there an approach that preserves the single-definition of validation, allows immediate client-side validation, and still provides the strength of server-side validation?

I'm familiar with the following two approaches:

  • ngval (https://github.com/alisabzevari/ngval)
  • http://www.danielroot.info/2013/09/hooking-angularjs-validation-to-aspnet.html

The first renders ng-validation syntax in Razor output, based on rules stated in the model. That seems like it couples me too tightly to building Razor views, when Razor views often won't intuitively pair with a well-organized Angular app. I could use this approach, but it seems it's more a result of someone wanting to replicate "Unobtrusive jQuery/MVC Validation", than building something well-suited to Angular.

The second approach just returns server-side validation back to Angular to render. It also doesn't do a thorough job of it. If needed I could run without client-side validation, since a single-page app still won't get screen flashes... but it's not ideal.

For example, maybe there is a toolset to more directly reflect the validation rules directly on WebAPIs and consume them in an Angular app. Or another approach that I haven't found?

At https://www.youtube.com/watch?v=lHbWRFpbma4#t=1336 , the presenter seems to imply this problem is already well-solved for Angular, and refers to specification (DDD Using Specification pattern for Validation). If you are aware of any tools that make this applicable to my problem, I'd love to hear it.

p.s. It seems like this is almost certainly an often-asked question. I'm sorry I was unable to find an answer here before posting

p.p.s. I'm currently planning to use Entity Framework, but I'd switch to address this. Heck, I'd consider switching to a whole different platform for this, my first Angular-focused project.

like image 916
shannon Avatar asked Sep 30 '14 00:09

shannon


1 Answers

The approach I recommend is based on @Esteban Felix commented and I used similar strategy in Java/Bean Validation and JSON schema generator.

Annotate your Domain model using Validate Model Data Using DataAnnotations

Generate schema using JSON.net other useful links

Create a AutoValidate directive that goes on and decorate fields with AngularJS build in directives for form validation e.g. ngPattern and simple things like min/max. In my case I created a mapping from Java world to AngularJS directives and wherever I needed we created custom directives.

like image 50
bhantol Avatar answered Nov 09 '22 18:11

bhantol