View model properties has changing validation rules at run time - c#

I'm new to C# MVC and I'm trying to add some dynamic validation checks to my view models that are used in a form. For example, I have a string property called FirstName. I can add the attribute StringLength(10) and Required() to it.
My problem is, depending on some other field, the FirstName StringLength could vary from 10 to 20, etc. I still want to use the MVC validations but be able to modify it. I know that attributes are bound to the class so maybe I'm using the wrong thing.
I want the abilities for attribute validation but have it modifiable at run time. Is this possible?

The values in an attribute have to be literals. You can still use attribute based validation, but you will need to use the CustomValidation tag and point it at a method to use. If it depends on multiple fields in the object, you will want to put this on the class rather than the property.

It seems you can add validation attributes at runtime by implementing DataAnnotationsModelValidatorProvider:
Dynamic Attributes # forums.asp.net

Related

How do I validate some fields some of the time?

I'm using C# in .Net-Core MVC and I have a form that users will need to fill out.
All of the fields that are shown on the page are required to be filled out. The issue I'm running into is that some of the fields on the form are hidden and others are displayed based on choices previously made on the form.
If I put the [Required] tag on all of the fields in the model, when I validate the ModelState, it flags the not displayed fields as invalid.
Is there a way that when I try to validate the ModelState, I can validate only the fields displayed on the page and ignore the fields that have been hidden?
Thanks.
Unfortunately the [Required] works globally in MVC.
You will need to develop your own validation attributes. Hopefully someone already did it but for MVC with .NET Framework (see the code here):
For validations that has the form of: “Validate this field only when
this other field has certain value”, I have coded 3 attributes:
RequiredIf, RangeIf and RegularExpressionIf that inherints from
ValidationAttribute.
Now you will need to translate it in order to work for .NET Core.
If you are looking for a more generic solution, the Web Forms framework has a very good concept of Validation group. It allows you to validate - or not - logically grouped properties.
If I put the [Required] tag on all of the fields in the model, when I
validate the ModelState, it flags the not displayed fields as invalid.
Of course cuz you set a parameter "Required". Disable that parameter from fields what can be not displayed or make nullable

How to implement UIHint attribute in mvc

I have gone through a couple of articles regarding UIHint attribute in mvc but none of them specifies clearly what it is or advantages of using it and also how to implement it in code.
Thanks!
The benefit of "UIHint" attribute is that it allows you to selectively apply the template. Let's say that you create an editor template for bool. If you name it "bool" it will automatically apply on all bool fields. But if you name it "abc123" you have the luxury of calling it selectively by decorating the property in your model with the "UIHint" attribute and only having it replace the default handlers as you desire.
It is easiest to understand that all types have a default handler so when you're using "TextboxFor", that too is applying a template, it just happens to be a native one as opposed to a custom template of your choosing.

Set the required field based on particular conditions

Is it possible to indicate a property is a required field without using data annotation attributes?
Instead of using annotation attributes, I want to set it as a required field, based on particular conditions.
For eg, something like below
if (true)
{
//set myObj.Name as required field
}
Edit: The reason why I need to do is, I'm calling a business service class of our own framework, which I can not touch, and inside the class, when the entity is being saved, mandatory checking is already catered.
But, in my requirement, I need to save my entity several times and , each times, the mandatory checking may be different . That's the reason why I need to mark the properties required fields dynamically.
Otherwise, I have to made my own mandatory checking before calling the business service class, which I don't want to do.
From your description, it seems like you need to provide your "own mandatory checking". I say this for two reasons;
To provide your user meaningful feedback as to why something field is required
Also, to satisfy the contract of your business service class
Can you have a "validate" method that simply runs through your set of rules (that mandatory checking, that you mentioned earlier) and have it return a list of strings indicating the rules that were violated on an attempt to save. Then you can use these strings to populate the text of a message box, logfile or whatever to provide meaningful feedback to the user as to why something wasn't saved, and also ensuring that data that is saved, is compliant to your business service class.

asp.net mvc ways for generating dynamic form fields at runtime

this is the more or less the schema i want to generate my dynamic form on based on the fields above. i am going to add the direction , max size, default value and like wise some more fields in it. i am looking for recommended ways and methods in asp.net mvc for generating dynamic fields at runtime.
1) if i design my own engine for it then how? i am interested on that also but this is the last thing i am looking at. method to apply validation is very important in my scenario
2) any framework that may lessen the working time? or anything else?
I'll describe the generic approach, I don't want to code it for you.
Create meta class to describe each field (type, name, maxlength, null value handling, data source for combos, etc.)
Load the data from database and preprocess it
Populate the ViewBag with sanitized values
Create helper that will generated the control specific code
Html.ControlFor("Name", metadata);
Loop in view over the metadata collection.
which will generate textbox, combobox, etc.
Remeber that MVC form handling works over list of key-values, it's the Binder feature that converts it to objects. Saving data won't be difficult (dynamically created INSERT, UPDATE statement, ...).

Adding and Removing Data Annotations from code

Is there away to add and remove DataAnnotations, in particular the [requried], from the code side of things? My problem is that I want to give the user the ability to save an incomplete form in our CRUD applications but at the same time use the power of the DataAnnotations validation.
If this is not possible, what is the best way I can go about this?
You can keep the DataAnnotation attributes on your model and then just manually clear the validation errors as needed from code. It might look something like this:
if (certainCondition == true) {
ModelState["someKey"].Errors.Clear();
ModelState["anotherKey"].Errors.Clear();
}
It is impossible to add, remove or modify DataAnnotations dynamically since they are Attributes. Attributes are part of the type and can't be changed during runtime.
You could use ModelState as Larsenal suggested provided that:
you use it After validation has executed. (prior to that, ModelState will be empty. It doesn't provide access to all validators, it only stores validator-errors after they've occurred)
you don't have any clientside validation that's based on the DataAnnotationValidators and fires errors that prevent you from even reaching the serverside validation.

Categories

Resources