angular2 validation: finding current validators on a control - angular2-forms

Angular RC4 How to add and remove Validation based on the state of other FormControls or FormGroups.
Based on this post Angular2 validator which relies on multiple form fields
In the example- It uses .compose to set multiple validators. It replaces the existing Validators with you new Validator.compose
this.form.controls["empID"].validator = Validators.compose([Validators.pattern("[0-9]{7}"), Validators.required]);
this.form.controls["empID"].updateValueAndValidity();
My issues is I can't find FormControl (.add or .remove) to change the current validation (one Validator at a time). If I want to add/remove Validators.required I would have to pull the current validators (another issue) and then add/remove require in the new .compose. (example above)
Am I overthinking this process. To add a validator dynamically works but only if I know all the validators.
One last thing I am try to make this generic by passing a control in and evaluate if another control is checked then apply/remove Validators accordingly.

Per Angular's documentation this isn't possible. On the AbstractControl documentation (which is the class that FormControl extends) there is no member to retrieve the current validators.
Unfortunately your only option is to use the two methods available to deal with validators:
setValidators() // Replaces all validators
clearValidators() // Removes all validators

Related

Is a Binder the only way to have automatic handling for a data-entry field being required in Vaadin 8 layout?

In Vaadin 8, the BinderBuilder::asRequired lets us define a Binder where a field is known to be required on a layout. If data is missing, the layout indicates to the user that the field needs to have data entered. This is great functionality, and smartly designed.
But using a Binder can be overkill for very small forms or dialog boxes. For one thing, we must define a data class to interact with the binder which can seem silly for a little form.
➙ Is there any other way to tap into Vaadin’s automatic handling of a required field without using a Binder?
In the Community Articles section of the manual, there is a page, Mark required fields as such. That page shows TextField as having setRequired and setRequiredError methods. But this seems incorrect. I can find no such methods on the latest TextField JavaDoc.
But using a Binder can be overkill for very small forms or dialog boxes. For one thing, we must define a data class to interact with the binder which can seem silly for a little form.
Yes. This is somewhat true. Thus I implemented FieldBinder tool. Which makes possible to use similar validator - converter chain as with Binder (it replicates the same API for applicable parts) with single field without Bean. Also it has the same facilities to handle validation status changes, uses same way to show required value, or validation error as Binder.
https://vaadin.com/directory/component/fieldbinder

Data annotation validation for multiple model properties

I'm currently using MVC data annotations for validating my form and it looks quite easy.
Now, I have a particular situation:
IF(checkbox1value = checked), then validate if textbox is not empty. If textbox is empty, then show validation error message.
How do I do this? Both checkbox and textbox are available as my model properties (bool and string respectively).
Is it possible to do this via a custom validation?
You can use a custom validator or IValidateableOject
There's a good explanation of both options here.
From the link.
If you need to support client validation, then a custom validator is what you want.
If your validation is strictly server side and you want to validate a number of business rules at once then use IValidateableObject.
I had to switch to Foolproof validation, which offered this functionality through it's RequiredIfTrue validator. I also really liked Fluent Validation since it was really flexible, and would also easily offer this functionality. Foolproof client-side support is provided for each of it's validators, where the boundary between client and server validation with Fluent Validation is not as easily distinguishable.

Is there anything out there to help handle "field level" authorization for ASP.NET MVC3?

I know you can use the Authorize attribute to control access to a Controller or ActionMethod... but what about more fine grained control? It seems common to have specific fields be allowed/disallowed based on a user's role, for instance. Maybe on an employee profile the employee can edit his profile information, but only a supervisor can change his job title...
Optimally I'd like to be able to develop views, models and controllers normally and have a configuration page on the website that site admins could then use to configure authorization at whatever granularity is required. In other words the programmers shouldn't worry about it (except for the guy writing/integrating that specific part of the system.)
I can envision DisplayFor and EditorFor checking attributes to render fields as ReadOnly, Hidden, etc... and maybe the attributes get added at run time from an Authorization Provider of some kind.
The question is: Is there a framework or something out there that already does this?
Write a custom ModelMetaDataProvider that will allow you to alter the metadata for each model and it's properties before they make it to the view. The built in helpers will not render a field if it's metadata value ShowForEdit = false or ShowForDisplay = false.
You can utilize a rules engine or some other ACL to manipulate the metadata on each model and property to get most of the behavior your looking for out of the box without touching the built in helpers. On edge cases where you need more control you can write your own helpers and pass more complex data in the metadata.AdditionalValues dictionary.
You can implement security at field level using HtmlHelper. In the following example they used textbox only implementation but it can easily be extended for all type of controls:
http://bartreyserhove.blogspot.ca/2008/12/field-level-security-using-aspnet-mvc.html

ASP.NET MVC 2 Custom Model Binding Question

Background
I have a payment page where the user can select from a list of existing payment methods, or specify a new one. The dropdown presents options such as:
Visa - ******1234 (Saved)
Mastercard - ******9876 (Saved)
[New Credit Card ...]
[New Electronic Check ...]
Using jQuery, I toggle hidden DIVs that contain either an informational table (in the case of options 1 or 2 for saved payment methods) or a form (in the case of the [new] options).
I am using a strongly typed class as my view model which contains (among simple types) a CreditCard class and a Check class. Each of these classes uses data annotation validators, as they are used in other parts of the site.
Problem
The problem comes in when the user submits the form. I would like to use model binding to handle the mapping of POST values, but I need the binding and/or validation to fire depending on which option the user selected. For example, if the user selects option 1 or 2 from the list above, I don't want the model validation (or maybe even the binding itself) to fire for the CreditCard or Check objects.
I have researched the possibilities of creating a custom model binder using IModelBinder as well as extending the DefaultModelBinder and just overriding some of the methods. However, I am unsure as to which method is better, and, if extending DefaultModelBinder, which would be the appropriate method to override.
The logic would be fairly simple:
If the user selected one of the existing payment methods, no validation on the CreditCard or Check are required.
If the user selected one of the options to create a new payment method, then only the selected method (CreditCard or Check) needs to be bound and validated
It feels as if extending the DefaultModelBinder is the way to go, as I would like most of the heavy lifting to be done by the framework without the need to create a custom binder from scratch. However, when looking at the available methods to override, it's not clear which is the best one(s):
BindProperty - The problem here is that I basically need to look at one of the properties to determine what other properties should be bound. I don't think I can control the order in which the incoming properties are bound, and I wouldn't want to rely on the order they are set in the HTML form.
OnModelUpdated - By this point, it's too late. The binding validation from the data annotations has been triggered and the ModelState has been updated. I would have to loop through the ModelState and remove the errors that are not relevant.
OnPropertyValidating - At first I thought this is where I should look, but even returning TRUE for all properties (as a test) causes the ModelState to contain binding errors.
I have come across this scenario in other aspects of the application and decided to split up functionality into separate controller/actions to simplify the process. However, I would like to have a better understanding of how to approach more complex UI problems, particularly related to the MVC model binding features.
Any help on this subject would be greatly appreciated.
All the possible values are stored in a dropdown list. Using jQuery, I toggle the form (for a new payment method) and the display (for an existing method)
I have decided to try to circumvent model binding altogether and use FormCollection, IValueProvider, and TryUpdateModel inside my controller action.
Your issue sounds way to specialized to be placed in the default ModelBinder.
The ModelBinder is this seductress that lures you in on the pretense that she can solve all of your problems. But then you start merging ModelState's together and going off to do crazy things with nested objects lists and before you know it she slaps you with divorce papers and takes everything but your bones.
MVC 3 holds some promise to provide a more extensible ModelBinder but from my own personal experience unless its super simple what you need to change, such as empty texboxes becoming "" instead of null, than stay clear away from your own implementation.
The alternative approach is to use the existing ModelBinder functionality piecemeal and using things like Ignore method parameters to clean things up:
if( myModel.IsNewPayment )
UpdateModel( myModel.Payment, "exclude everything else" );
A lot of what your proposing to stuff into the model binder is really business logic too that should be in another layer. I've done some crazy things with my own ModelBinder and now regret every line of code I've written in there. Maybe its just me but your really bending the rules and completely trashing the "single responsibility principal" by putting business and payment logic in there.

Combine DataAnnotations Validation with complex business rules

I understand annotating class properties with the basic required and minimum length and getting all the benefits of the asp.net mvc server side and client side validation.
However does anyone have a link that shows how you combine this 'base' validation with more complex business rules. How would I run business rule functions, such as for example, has the customer ordered anything in the last year (database hit required) and still use the same DataAnnotation and mvc validation plumbing?
Goal : Don't want two ways of generating and outputting validation methods.
From http://msdn.microsoft.com/en-us/library/dd901590%28VS.95%29.aspx:
To create customized validation checks, you can either create a class that derives from the ValidationAttribute class or create a method that performs the validation check and reference that method when applying the CustomValidationAttribute to the data member. When you create a class that derives from ValidationAttribute, override the IsValid method to provide the logic for your customized validation check.
There appears to be example code there.
Data Annotation run before your action is invoked. Then, regardless whether the validation succeded or not, the action is still called. If the DA detected invalid data, your ModelState will be invalid.
Once here, you can still do any validation you want, for your business rules, as you would normally do without the data annotation, if you want to. In your action, you can add errors to the ModelState even if the Data Annotation validation passed.
In this case, you add your errors with ModelState.addError, and those errors are added to any error provided by the DA. So in your View it doesn't matter where the error comes from.
Or, if your rules are general, you can write your own annotation tags. The Data Annotation thing is distributed with its source, so you have full control on it.
You could use VAB (Application Validation Block) from the Enterprise Library 5 of Microsoft that actually based on the DataAnnotations class but u do your complex bussiness logic very easily through configuration...
i'd suggest you check it out...
Have a look at following article, where you can use DataAnnotations Multiple Times On Same Field, Compare N number of properties and N number of values....
http://www.codeproject.com/KB/validation/MultipleDataAnnotations.aspx

Resources