How do I validate some fields some of the time? - c#

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

Related

Not getting data-val attributes for GUID

I'm working on a bigger project and we have many views and almost all of them have a SelectList or more, whose value is a GUID. The viewmodel works fine and server side validation as well, the problem is that the HTML select element does not get any data-val attributes, we are using Html.DropDownListFor. It works fine when the value is short, string etc but not GUID.
Is there a way to get data-val attributes without adding an ValidationAttribute to all GUID properties in the viewmodels? Because there are a loot of them.
What worked for me in the end:
I got on the right track with Stephen Muecke's answer: we are using our own RequiredAttribute:
public class LocalizedRequiredAttribute : RequiredAttribute
{
public LocalizedRequiredAttribute()
{
ErrorMessageResourceName = "Required";
ErrorMessageResourceType = typeof (Resources.ErrorMessages);
}
}
But this does not add any client side validation attributes like the basic [Required] does, but it was easy to fix. Just add this code to your Application_Start():
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof (LocalizedRequiredAttribute),
typeof (RequiredAttributeAdapter));
And now you will get data-val=true data-val-required="message".
Solution found here: https://stackoverflow.com/a/12573540/1225758
No data-val-* attributes are rendered because there are no jquery.validate.unobtrusive adaptors for GUID. The only one you could get out of the box is data-val-required (and the associated data-val) if you were to make the property nullable and add the [Required] attribute.
If you want some client validation you could use a [RegularExpression] attribute (not tested but I think ^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$ should work).
However it seems unnecessary since you are using #Html.DropDownListFor() and (I assume) your building a SelectList on the controller which would contain only GUID's for the SelectListItem.Value property (why would you render an option which is not valid - other than perhaps a "--Please select--" label option for use with a [Required] attribute?).
Firstly, I would want to know what the problem is with having multiple GUID data annotations on your model properties?
Secondly I would say that it is far clearer and readable to other developers working on the project to have explicit validation going on with data annotations on each property than it is to have some "non-standard" validation voodoo going on.
You could probably achieve this with action filters (look for any properties of type Guid) but I think this will make the use/specification of your models less expressive of their intentions and simply confuse.
Guids have dashes in content and may occur problems. You may try to use .ToString('N') at the end of the Guids where they are being generated to remove dashes. Or you may write a jquery hack to add escape characters before dashes on client side. Or even more; try to implement your own guid validation approach as here: How to test valid UUID/GUID?
Or even even more, you can try to implement your own guid annotation attribute as here:
Validation of Guid

Multiple custom validation attribute on single property

I am working on a MVC 4 project. I am having an issue with multiple custom validation attribute on single property. Suppose I have 3 custom validation attribute for single property such as:
public class Test
{
[customAttribute1]
[customAttribute2]
[customAttribute3]
public string property1 { get; set; }
}
Currently when I post he form than all three custom validations are performed on the property (no matter whether first validation pass or fail).
What I want is if customAttribute1 validation fails than no need to validate the property with next next custom attribute. How can i achieve this?
The point of this behaviour is to return back (to the UI) all the errors in the Model, so the user can fix all the errors at the same time...
Let's say you want you password to be minimum 8 chars and have at least an uppercase and a number. The way you want your validation to run is to stop if the password is not long enough without checking the rest. Typical use case scenario:
User sets password "foo" -> submit
error - Password too short
User sets it to "foofoofoo"
error - Password must have an uppercase
User sets it to "FooFooFoo"
error - Password must have a number
User goes away frustrated...
So, if the 3 attributes are to be validated together, my suggestion is to keep this behaviour. If the 3 are exclusive then do as others suggested and combine them into a single attribute.
Ordering or executing conditionally is not supported AFAIK.
The best bet is to have all these 3 validations in the same attribute.
If you are badly in need of this kind of validation, then Fluent Validation can do it for you.

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, ...).

Multiple field searches in MVC 3 using C #

Hi I am relatively new to MVC 3. i was just wondering if there is a way to do multiple field searches.
I'm looking to have many textboxes on a page, where the user can input search criteria such as Region, Salesperson Rating, Salesperson Subject, etc .
and then when the user clicks the search button it should populate a list with Salespeople matching the criteria entered.
I have been looking on the web and i haven't found a concrete answer...
Thank you in advance...
You could use a grid like jqgrid to get these kinds of functionalities. It's relatively easy to implement in asp.net mvc. I once wrote a mvc helper for jqgrid, it's built for mvc2 but can also be used in mvc3 as well. There's also a sample app for the helper, you can find it here to see if fits your needs.
Yes, you can have multiple parameters passed to a controller action, e.g. by defining a form with multiple input fields in your view and let the form post to the action url. The data can be passed using multiple method parameters, a custom model class that defines the relevant properties, or simply by using a form collection.

View model properties has changing validation rules at run time

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

Categories

Resources