1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TerryLi
  • 221
  • 1
  • 7
  • 13

3 Answers3

1

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/

Reza Ahmadi
  • 862
  • 2
  • 11
  • 23
0

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

Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41
0
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.
Pankaj Rupapara
  • 752
  • 4
  • 9