ASP.NET MVC3 conditional validation - checkbox > editor - asp.net-mvc-3

I would like to have a bool field and and a string field in my Model and not having any validation attributes on them.
But in the view I would like to have the required field validation on the Editor if the Checkbox is checked.
How do I do this please?
Thank you.

You can still use the data annotations attributes and follow any of this option.
Clear the errors from the modelstate dictionary for that field inside the action
Use the conditional validation library created by simon.
Ex.
public class ValidationSample
{
[RequiredIf("PropertyValidationDependsOn", true)]
public string PropertyToValidate { get; set; }
public bool PropertyValidationDependsOn { get; set; }
}

Related

Is there a way in MVC3 to define data validation annotation for a group in a class?

I am new to MVC, recently I am working on the data validation, and I was wondering that in stead of giving a validation annotation for each parameter, is there a way that I can define validation rules for a group of parameters in a class? For example, a class is like this:
namespace MvcApplication1.Models
{
public class Product
{
public int Id { get; set; }
[Required]
[StringLength(10)]
public string Param1 { get; set; }
[Required]
public string Param2 { get; set; }
[DisplayName("Param3")]
[Required]
public string Param3 { get; set; }
}
}
Is there a way to define a rule that for Param1, Param2, and Param3, for example, at least 2 of them are required?
So easy to use. try this one.
MVC Foolproof Validation
and this is how you can build your own custom validation.
http://www.nickriggs.com/posts/build-model-aware-custom-validation-attributes-in-asp-net-mvc-2/
For more advanced validation like this, I would recommend FluentValidation
http://fluentvalidation.codeplex.com/
You can create your own custom validators:
http://fluentvalidation.codeplex.com/wikipage?title=Custom&referringTitle=Documentation
DataType
Specify the datatype of a property
DisplayName
specify the display name for a property.
DisplayFormat
specify the display format for a property like different format for Date proerty.
Required
Specify a property as required.
ReqularExpression
validate the value of a property by specified regular expression pattern.
Range
validate the value of a property with in a specified range of values.
StringLength
specify min and max length for a string property.
MaxLength
specify max length for a string property.
Bind
specify fields to include or exclude when adding parameter or form values to model properties.
ScaffoldColumn
specify fields for hiding from editor forms.

ASP.Net MVC 3 DataAnnotations validating List<T>

I have a ViewModel that has been deserialized from JSON which looks something like this:
public class UserThingsUpdateViewModel
{
public IList<Thing> Things { get; set; }
[Required]
public int UserId { get; set; }
public int Age { get; set; }
}
Thing is also a ViewModel which also has various DataAnnotaion ValidationAttribute attributes on the properties.
The problem is that Lists don't seem to get validated and even after a through search I cant seem to find any articles that tackle this. Most suggest that the ViewModel is wrong if it includes a list.
So, what is the best way to validate my list and add Model Errors to the Model State?
Prior to checking ModelState.IsValid, you could add code to step through and validate each Thing, as follows:
foreach (var thing in Things)
TryValidateModel(thing);
This will validate each item, and add any errors to ModelState.
You could write a custom validator attribute and decorate the list property with it? That would allow you to write custom logic to get the elements out of the list and validate them.

MVC3 DataAnnotaions validation

is there a way to use conditional validation on MVC3 model?
for example:
public class User
{
[Required]
public string Password { get; set; }
[Required, Compare("Password")]
public string ComparePassword { get; set; }
}
Where i would like Password and confirmpassword fields to be required ONLY when adding a new user. However when editing I would like these to be empty (text boxes in the view). Only when user does type in a new Password and ConfirmPassword will the password be changed in the DB.
Thanks
Typically you would have separate AddUserViewModel and EditUserViewModel classes with the appropriate fields and validators. Then in your controller action if the model is valid, you convert to your view models to your User entity and pass it on to your business logic / service to save. You can use Automapper for this.

ASP.NET - MVC3 property decoration?

Is there an attribute I can decorate a single property on my model to tell the engine not to include the property in the validation routine?
[DoNotValidate] or [ValidateIgnore]
----------------------More info.
Ok, I need to give you more information. In my situation, I have a temporary decimal value on my model that is not persisted, that gets formatted into currency. $540,000.
In this one case I do not want to strip the formatting out before I call TryUpdateModel. When you use TryupdateModel, it mvc will try and convert that string text box value back into a decimal and Model.IsValid will return false. I know how to get around this situation, using javascript, but it would be easier if I could tell mvc not to validate that field.
Any model properties not decorated with validation attributes should be ignored.
public class MyModel
{
[Required]
public string SomeProperty { get; set; }
public string IgnoredProperty { get; set; }
}
Should validate that SomeProperty is required, but nothing will happen with IgnoredProperty.
The best tutorial IMHO on Model validation is http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
(even though it says for MVC 2, it's applicable).
Change the type of your decimal to nullable decimal to prevent required validation:
public class MyModel
{
public decimal MyValidatingDecimal { get; set; }
public decimal? MyNonValidatingDecimal { get; set; }
}
MyValidatingDecimal will be required (since it is a value-type), while MyNonValidatingDecimal will not be required.
Properties will only be validated if you explicitly apply validation attributes to them.

How dynamically set validation attributes to a Model MVC 2?

Lets says I have the following model
public class Person
{
[NameIsValid]
public string Name { get; set;}
public string LastName { get; set; }
}
I created a custom attribute NameIsValid for this model.
Lets says for ViewA I need the custom attribute validation in the model, but for ViewB I dont need this custom validation attribute.
How can I dynamically set or remove the custom attribute from the model when need it?
Thanks!
Don't put any validation in ViewB :
Client-side :
#Html.ValidateFor(x => x.Name)
Nor server-side :
if(ModelState.IsValid)
{...}

Resources