CustomValidation 属性不适用于 ASP.NET MVC 3 和 EF

发布于 2024-12-10 16:22:53 字数 2892 浏览 0 评论 0 原文

我了解如何创建自定义验证属性。事实上,当我使用 Seed 方法预填充数据库时,Validate 方法正在执行,如果失败就会抛出异常。 但是,验证不适用于实体的创建表单。

我是否必须对 HTML(Razor 表单)进行一些更改?

它只是让我添加验证失败的项目。

代码在这里:

namespace Data.Model
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed public class YearsValidationAttribute : ValidationAttribute
    {
        // Internal field to hold the min value.
        readonly int _years;

        public int Years
        {
            get { return _years; }
        }

        public YearsValidationAttribute(int years)
        {
            _years = years;
        }


        public override bool IsValid(object value)
        {
            var years = (int)value;
            bool result = true;
            if (this.Years != null)
            {
                result = Years >= years;
            }
            return result;
        }



        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture,
              ErrorMessageString, name, Years);
        }
    }
}


public class Position
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]   
        public int PositionID { get; set; }

        [Required(ErrorMessage = "Position name is required.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
        [Display(Name = "Position name")]              
        public string name { get; set; }

        [Required(ErrorMessage = "Number of years is required")] 
        [Display(Name = "Number of years")]
        [YearsValidationAttribute(5, ErrorMessage = "{0} value must be greater than {1} years.")]        
        public int yearsExperienceRequired { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }



@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Position</legend>

        @Html.HiddenFor(model => model.PositionID)

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

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

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

I understood how to create custom validation attributes. In fact, the Validate method is being execute when I use the Seed method to pre-populate the database, and if it fails it throws an exception.
However, the validation is not working on the Create Form of the entity.

Do I have to change something to the HTML (Razor Form)?

It just lets me add items that fail the validation.

Code here:

namespace Data.Model
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed public class YearsValidationAttribute : ValidationAttribute
    {
        // Internal field to hold the min value.
        readonly int _years;

        public int Years
        {
            get { return _years; }
        }

        public YearsValidationAttribute(int years)
        {
            _years = years;
        }


        public override bool IsValid(object value)
        {
            var years = (int)value;
            bool result = true;
            if (this.Years != null)
            {
                result = Years >= years;
            }
            return result;
        }



        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture,
              ErrorMessageString, name, Years);
        }
    }
}


public class Position
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]   
        public int PositionID { get; set; }

        [Required(ErrorMessage = "Position name is required.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
        [Display(Name = "Position name")]              
        public string name { get; set; }

        [Required(ErrorMessage = "Number of years is required")] 
        [Display(Name = "Number of years")]
        [YearsValidationAttribute(5, ErrorMessage = "{0} value must be greater than {1} years.")]        
        public int yearsExperienceRequired { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }



@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Position</legend>

        @Html.HiddenFor(model => model.PositionID)

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

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

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

楠木可依 2024-12-17 16:22:53

您拥有的代码不会为您提供客户端验证器,而只会为您提供服务器端。但这是一个很好的起点。您需要在服务器上的操作方法中执行的操作是检查模型是否有效,如下所示:

public ActionResult YourAction(YourModel model)
{
    if(ModelState.IsValid)
    {
        // Do your save
    }
    else
    {
        // Do your other stuff
    }
}

如果您还需要客户端验证,则可以使用此处的资源:http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

您还可以尝试使用Remote验证属性:http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

That code you have won't give you a client validator, only the server side. But that is a good starting point. What you need to do in your action method on the server is to check if the model is valid like such:

public ActionResult YourAction(YourModel model)
{
    if(ModelState.IsValid)
    {
        // Do your save
    }
    else
    {
        // Do your other stuff
    }
}

If you want client side validation as well you can use the resources here: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

You can also try to use the Remote validation attribute: http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文