简体   繁体   English

按需添加dataAnnotation以验证表单+ mvc4

[英]Add dataAnnotation on demand to validate a form + mvc4

I need to validate a form, this is my model: 我需要验证一个表单,这是我的模型:

 public class Movie {
    public int ID { get; set; }

    [Required]
    public string Title { get; set; }

    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }

    [Required]
    public string Genre { get; set; }

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    [StringLength(5)]
    public string Rating { get; set; }
}

My question is: I have a querystringParam that contain a cinemaId, when i read this param i read from database a configuration of each property is required or no. 我的问题是:我有一个包含CinemaId的querystringParam,当我读取此参数时,我从数据库中读取了每个属性的配置是否必需。 Sometimes I need to add [Required] to the property and sometimes No, How can i do this please?? 有时我需要在属性中添加[Required] ,有时则不行,请问该怎么办?

You have to modify the ModelState in the controller actions. 您必须在控制器操作中修改ModelState

In your post action, load the database configuration check each property, and add the errors to the ModelState property like this: 在发布操作中,加载数据库配置,检查每个属性,然后将错误添加到ModelState属性,如下所示:

if (/* the property value is wrong */)
{
  ModelState.AddModelError("propertyName", "message");
}

These errors will be treated just as if they had been generated by MVC framework using the data annotations (adding styles to rendered controls, appearing in the list of errors and so on). 这些错误将被视为如同它们是由MVC框架使用数据注释生成的一样(将样式添加到呈现的控件中,出现在错误列表中,等等)。

If the property is nested use dots, like this: "property.subproperty.subproperty" for the property name parameter. 如果该属性是嵌套的,则使用点,例如:属性名称参数为"property.subproperty.subproperty"

Building up on the answer @JotaBe gave, you could use a custom validation attribute on the Model property itself. 在给出的@JotaBe答案的基础上,您可以在Model属性本身上使用自定义验证属性。 Something like this : 像这样的东西:

Conditional Required Attribute 条件必填属性

public class ConditionalRequiredAttribute : ValidationAttribute
{
    private const string DefaultErrorMessageFormatString 
                   = "The {0} field is required.";

    private readonly string _dependentPropertyName;

    public ConditionalRequiredAttribute(string dependentPropertyName)
    {
        _dependentPropertyName = dependentPropertyName;
        ErrorMessage = DefaultErrorMessageFormatString;
    }

    protected override ValidationResult IsValid(
                object item, 
                ValidationContext validationContext)
    {
        var property = validationContext
                         .ObjectInstance.GetType()
                         .GetProperty(_dependentPropertyName);

        var dependentPropertyValue = 
                            property
                            .GetValue(validationContext.ObjectInstance, null);

        int value;
        if (dependentPropertyValue is bool 
                           && (bool)dependentPropertyValue)
        {
            /* Put the validations that you need here */
            if (item == null)
            {
              return new ValidationResult(
                  string.Format(ErrorMessageString, 
                                validationContext.DisplayName));
            }
        }

         return ValidationResult.Success;
    }
}

Applying the Attribute 应用属性

Here I have a class Movie and the Rating is required depending on the value of RatingIsRequired boolean property which can be set from the server. 在这里,我有一个Movie类,并且需要Rating,这取决于可以从服务器设置的RatingIsRequired布尔属性的值。

public class Movie
{
   public bool RatingIsRequired { get; set; }

   [ConditionallyRequired("RatingIsRequired"]   
   public string Rating { get; set; }
}
  1. With this the ModelState.IsValid will return false if RatingIsRequired set to true and Rating is empty. 这样,如果将RatingIsRequired设置为true并且Rating为空,则ModelState.IsValid将返回false。
  2. Also You can write a custom unobtrusive jquery validator to for client enabled validations so that is works like regular [Required] attribute. 另外,您可以编写一个自定义的,不打扰的jquery验证程序以进行客户端启用的验证,因此它的工作方式类似于常规[Required]属性。

Let me know if this helps. 让我知道是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM