【问题标题】:Fluent Validation breaks in ASP .Net MVC ApplicationASP .Net MVC 应用程序中的流利验证中断
【发布时间】:2016-03-04 18:05:30
【问题描述】:

我一直在面对这个问题,并尝试了各种方面。直到现在什么都没有解决。这就是我所拥有的。我有一个 Student.cs 域模型类。

   [FluentValidation.Attributes.Validator(typeof(StudentViewModelValidator))]
public class Student
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StudentId { get; set; }
    public String LastName { get; set; }
    public String FirstName { get; set; }
    public String UserName { get; set; }
    public String Password { get; set; }

    [ForeignKey("Department")]
    public int DepartmentID { get; set; }

    //Department Navigational Property
    public Department Department { get; set; }
}

还有一个 StudentViewModel 类:

//View Model
public class StudentViewModel
{
    public Student Student { get; set; }

    [Display(Name = "StudentName")]
    public String StudentFullName
    {
        get
        {
            return String.Format("{0} {1}", Student.FirstName, Student.LastName);
        }
    }

    [DataType(DataType.Password)]
    public String Password { get; set; }

    [DataType(DataType.Password)]
    [Compare("Password",ErrorMessage="Passwords do not match")]
    [Display(Name="Confirm Password")]
    public String C_Password { get; set; }

    [Display(Name = "Department Name")]
    public String DepartmentName { get; set; }

}

部门模型类看起来像:

   public class Department
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DepartmentID { get; set; }

    //[Required(ErrorMessage="Department Name cannot be empty")]
    public String DepartmentName { get; set; }

    //[Required(ErrorMessage = "Department Code cannot be empty")]
    public String DepartmentCode { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

FluentValidation 规则如下所示:

    public class StudentViewModelValidator : AbstractValidator<Student>
{
    public StudentViewModelValidator()
    {
        RuleFor(m => m.FirstName)
            .NotEmpty().WithMessage("First Name is required.")
            .Matches(@"^\D*$").WithMessage("Special characters and numbers are not allowed in First Name");
        RuleFor(m => m.LastName)
            .NotEmpty().WithMessage("Last Name is required.")
            .Matches(@"^\D*$").WithMessage("Special characters and numbers are not allowed in Last Name");
        RuleFor(m => m.UserName)
            .NotEmpty().WithMessage("User Name is required.")
            .Matches(@"^a-zA-Z0-9\.\$").WithMessage("Only . and $ are allowed special characters in a user name");
        RuleFor(m => m.Password)
            .NotEmpty().WithMessage("Password is required.")
            .Length(4, 10).WithMessage("Password should be 4 to 10 characters long")
            .Matches(@".*\d{2}").WithMessage("Password should contain at least 2 digits")
            .Matches(@".*a-zA-Z").WithMessage("Password should contain at least one albhabet")
            .Matches(@"[\.\$\~\&]").WithMessage("Allowed special characters in a password are . $ ~ &");
   
    }
}

验证不断打破说法

不显眼的客户端验证规则中的验证类型名称必须是唯一的。不止一次看到以下验证类型:正则表达式

Password 字段。

视图看起来像:

  @model MvcApplication4.Models.Student

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    @using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend><strong>Create a record</strong></legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DepartmentID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DepartmentID)
            @Html.ValidationMessageFor(model => model.DepartmentID)
        </div>

        <p>
            <input type="submit" class="createDetails" value="Create" />
        </p>
    </fieldset>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

更新

如果我把这些行放在Application_Start()

//var fluentValidationModelValidatorProvider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());
            //ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);
            //DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
            //fluentValidationModelValidatorProvider.AddImplicitRequiredValidator = false;

然后验证在LastName 字段处中断。

请帮我解决。

【问题讨论】:

  • 密码验证中是否只有一个 .matches 有效?
  • 不,它没有。它仍然在 LastName 中显示错误。当我从 FluentValidator 注释出 LastName 的代码块时,它显示 FirstName 的错误。

标签: c# asp.net regex asp.net-mvc validation


【解决方案1】:

这个问题可能是由于为同一个键设置了多个值

因为 ValidatonMessage 是字典类型。

删除视图模型上的所有装饰/数据注释并使用 fluentvalidator,它就可以工作了。

请参考

Validation type names in unobtrusive client validation rules must be unique

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多