MVC3 项目从另一个属性设置字符串长度验证值

本文关键字:验证 字符串 设置 项目 另一个 属性 MVC3 | 更新日期: 2023-09-27 18:36:21

我有一个 mvc razor 页面,其中包含一个表单,其中包含从数据库动态创建的字段,即字段名称、类型(文本框等)在 db 表中设置以及 StringLength

我的模型中是否有某种方法可以将字段上的 StringLength 设置为其他属性之一的值?

这些问题是使用问题模型的编辑器模板构建的,这些是问题模型中的相关字段;

public string QuestionTypeName { get; set; }  --> ie this is like TextBox, TextArea etc and is used to create the write EditorTemplate
[RequiredIf("Required", true)]
[StringLength(<<this is where I want to use the property FieldLength>>)]
public string Answer { get; set; }
[DisplayName("Question name")]
public string Question { get; set; }
public bool Required { get; set; }
public Int32 FieldLength { get; set; }

MVC3 项目从另一个属性设置字符串长度验证值

您可以按如下方式编写自己的Custom Validation Attribute

实现

    public class CustomValidation : ValidationAttribute
    {
          public CustomValidation(string otherproperty)
          : base("Your Error Message goes here")
          {
              OtherProperty = otherproperty;
          }
          public string OtherProperty { get; set; }
          public override string FormatErrorMessage(string name)
          {
               return string.Format(ErrorMessageString, name, OtherProperty);
          }
          protected override ValidationResult IsValid(object firstobject, ValidationContext validationContext)
          {
                var firstValue = firstobject;
                var secondValue = GetSecondObject(validationContext);
          if(firstValue !=null && secondValue!=null)
          {
                if (//Your Condition for validation failure)
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }               
          }
                return ValidationResult.Success;
          }
         protected object GetSecondObject(
ValidationContext validationContext)
         {
                var propertyInfo = validationContext
                              .ObjectType
                              .GetProperty(OtherProperty);
               if (propertyInfo != null)
               {
                    var secondValue = propertyInfo.GetValue(
                    validationContext.ObjectInstance, null);
                    return secondValue as object;
               }
              return null;
        }
  }

用法:

public class ClassName
{
    [CustomValidation("FieldLength")] // pass the property name 
    public string Answer { get; set; }
    .....

试试这个

[StringLength(50, MinimumLength=10)]
public string Answer { get; set; }

或使用最大长度,并查看此链接以获取字符串长度属性