MVC 3模型的复杂验证

时间:2011-11-02 10:51:11

标签: asp.net-mvc-3 validation idataerrorinfo

在MVC 3中使用的当前验证方法似乎是ValidationAttributes。我有一个非常特定于该模型的类验证,并且具有几个属性之间的交互。

基本上,该模型具有其他模型的集合,并且它们都以相同的形式进行编辑。我们称之为ModelA,它有一个ModelB的集合。我可能需要验证的一件事是,ModelB的某些属性的总和小于ModelA的属性。用户可以在一些选项中划分X个分数。

ValidationAttributes非常通用,我不确定它们是否适合这项工作。

我不知道MVC 3中是如何支持IDateErrorInfo的,以及它是否可以直接使用。

一种方法是通过方法验证,但这意味着我无法进行客户端验证。

做这样的事情的正确方法是什么?我还有其他选择吗?我低估了ValidationAttribute的强大功能吗?

4 个答案:

答案 0 :(得分:5)

IDateErrorInfo

MVC框架支持IDateErrorInfo(可以找到Microsoft教程here)。默认模型绑定器将通过将html表单元素绑定到模型来重新创建模型对象。如果模型绑定器检测到模型实现了接口,那么它将使用接口方法来验证模型中的每个属性或作为整体验证模型。有关更多信息,请参阅教程。

如果您想使用此方法使用客户端验证,那么(引用Steve Sanderson)“利用其他验证规则的最直接方法是在视图中手动生成所需的属性”:

<p>
@Html.TextBoxFor(m.ClientName, new { data_val = "true", data_val_email = "Enter a valid email address", data_val_required = "Please enter your name"})

@Html.ValidationMessageFor(m => m.ClientName)
</p>

然后,可以使用它来触发已定义的任何客户端验证。有关如何定义客户端验证的示例,请参阅下文。

明确验证

正如您所提到的,您可以明确地在操作中验证模型。例如:

public ViewResult Register(MyModel theModel)
{
    if (theModel.PropertyB < theModel.PropertyA)
        ModelState.AddModelError("", "PropertyA must not be less then PropertyB");

    if (ModelState.IsValid)
    {
        //save values
        //go to next page
    }
    else
    {
        return View();
    }
}

在视图中,您需要使用@Html.ValidationSummary来显示错误消息,因为上面的代码会添加模型级别错误而不是属性级别错误。

要指定属性级别错误,您可以写:

ModelState.AddModelError("PropertyA", "PropertyA must not be less then PropertyB");

然后在视图中使用:

@Html.ValidationMessageFor(m => m.PropertyA);

显示错误消息。

同样,任何客户端验证都需要通过定义属性在视图中的客户端验证中手动链接来链接。

自定义模型验证属性

如果我正确理解了这个问题,那么您正在尝试验证包含单个值的模型以及要对该集合上的属性求和的集合。

对于我将给出的示例,视图将向用户显示最大值字段和5个值字段。最大值字段将是模型中的单个值,其中5个值字段将成为集合的一部分。验证将确保值字段的总和不大于最大值字段。验证将被定义为模型上的属性,该属性也将很好地链接到javascript客户端版本。

视图:

@model MvcApplication1.Models.ValueModel

<h2>Person Ages</h2>

@using (@Html.BeginForm())
{
    <p>Please enter the maximum total that will be allowed for all values</p>
    @Html.EditorFor(m => m.MaximumTotalValueAllowed)
    @Html.ValidationMessageFor(m => m.MaximumTotalValueAllowed)

    int numberOfValues = 5;

    <p>Please enter @numberOfValues different values.</p>

    for (int i=0; i<numberOfValues; i++)
    {
        <p>@Html.EditorFor(m => m.Values[i])</p>
    }

    <input type="submit" value="submit"/>
}

我没有对值字段添加任何验证,因为我不想过度复杂化示例。

模特:

public class ValueModel
{
    [Required(ErrorMessage="Please enter the maximum total value")]
    [Numeric] //using DataAnnotationExtensions
    [ValuesMustNotExceedTotal]
    public string MaximumTotalValueAllowed { get; set; }

    public List<string> Values { get; set; }
}

行动:

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(ValueModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    else
    {
        return RedirectToAction("complete"); //or whatever action you wish to define.
    }
}

自定义属性:

可以通过覆盖ValidationAttribute类来定义模型上定义的[ValuesMustNotExceedTotal]属性:

public class ValuesMustNotExceedTotalAttribute : ValidationAttribute
{
    private int maxTotalValueAllowed;
    private int valueTotal;

    public ValuesMustNotExceedTotalAttribute()
    {
        ErrorMessage = "The total of all values ({0}) is greater than the maximum value of {1}";
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, valueTotal, maxTotalValueAllowed);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropertyInfo maxTotalValueAllowedInfo = validationContext.ObjectType.GetProperty("MaximumTotalValueAllowed");
        PropertyInfo valuesInfo = validationContext.ObjectType.GetProperty("Values");

        if (maxTotalValueAllowedInfo == null || valuesInfo == null)
        {
            return new ValidationResult("MaximumTotalValueAllowed or Values is undefined in the model.");
        }

        var maxTotalValueAllowedPropertyValue = maxTotalValueAllowedInfo.GetValue(validationContext.ObjectInstance, null);
        var valuesPropertyValue = valuesInfo.GetValue(validationContext.ObjectInstance, null);

        if (maxTotalValueAllowedPropertyValue != null && valuesPropertyValue != null)
        {
            bool maxTotalValueParsed = Int32.TryParse(maxTotalValueAllowedPropertyValue.ToString(), out maxTotalValueAllowed);

            int dummyValue;
            valueTotal = ((List<string>)valuesPropertyValue).Sum(x => Int32.TryParse(x, out dummyValue) ? Int32.Parse(x) : 0);

            if (maxTotalValueParsed && valueTotal > maxTotalValueAllowed)
            {
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
            }
        }

        //if the maximum value is not supplied or could not be parsed then we still return that the validation was successful.
        //why?  because this attribute is only responsible for validating that the total of the values is less than the maximum.
        //we use a [Required] attribute on the model to ensure that the field is required and a [Numeric] attribute
        //on the model to ensure that the fields are input as numeric (supplying appropriate error messages for each).
        return null;
    }
}

将客户端验证添加到自定义属性:

要向此属性添加客户端验证,需要实现IClientValidatable接口:

public class ValuesMustNotExceedTotalAttribute : ValidationAttribute, IClientValidatable
{
//...code as above...

    //this will be called when creating the form html to set the correct property values for the form elements
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule {
            ValidationType = "valuesmustnotexceedtotal", //the name of the client side javascript validation (must be lowercase)
            ErrorMessage = "The total of all values is greater than the maximum value." //I have provided an alternative error message as i'm not sure how you would alter the {0} and {1} in javascript.
        };

        yield return rule;
        //note: if you set the validation type above to "required" or "email" then it would use the default javascript routines (by those names) to validate client side rather than the one we define
    }
}

如果您此时要运行应用程序并查看定义属性的字段的源html,您将看到以下内容:

<input class="text-box single-line" data-val="true" data-val-number="The MaximumTotalValueAllowed field is not a valid number." data-val-required="Please enter the maximum total value" data-val-valuesmustnotexceedtotal="The total of all values is greater than the maximum value." id="MaximumTotalValueAllowed" name="MaximumTotalValueAllowed" type="text" value="" />

特别注意data-val-valuesmustnotexceedtotal的验证属性。这就是我们的客户端验证将链接到验证属性的方式。

添加客户端验证:

要添加客户端验证,您需要在视图的标记中添加以下类似的库引用:

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

您还需要确保在web.config中启用客户端验证,尽管我认为默认情况下应该启用它:

<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

剩下的就是在视图中定义客户端验证。请注意,此处添加的验证是在视图中定义的,但如果它是在库中定义的,那么自定义属性(可能不是这个)可以添加到其他模型中以用于其他视图:

<script type="text/javascript">

    jQuery.validator.unobtrusive.adapters.add('valuesmustnotexceedtotal', [], function (options) {
        options.rules['valuesmustnotexceedtotal'] = '';
        options.messages['valuesmustnotexceedtotal'] = options.message;
    });

    //note: this will only be fired when the user leaves the maximum value field or when the user clicks the submit button.
    //i'm not sure how you would trigger the validation to fire if the user leaves the value fields although i'm sure its possible.
    jQuery.validator.addMethod('valuesmustnotexceedtotal', function (value, element, params) {

        sumValues = 0;

        //determine if any of the value fields are present and calculate the sum of the fields
        for (i = 0; i <= 4; i++) {

            fieldValue = parseInt($('#Values_' + i + '_').val());

            if (!isNaN(fieldValue)) {
                sumValues = sumValues + fieldValue;
                valueFound = true;
            }
        }

        maximumValue = parseInt(value);

        //(if value has been supplied and is numeric) and (any of the fields are present and are numeric)
        if (!isNaN(maximumValue) && valueFound) {

            //perform validation

            if (sumValues > maximumValue) 
            {
                return false;
            }
        }

        return true;
    }, '');

</script>

那应该是它。我确信可以在这里和那里进行改进,如果我稍微误解了这个问题,你应该能够根据需要调整验证。但我相信这种验证似乎是大多数开发人员编写自定义属性的方式,包括更复杂的客户端验证。

希望这会有所帮助。如果您对上述内容有任何疑问或建议,请与我们联系。

答案 1 :(得分:1)

这就是你要找的东西:

http://www.a2zdotnet.com/View.aspx?Id=182

答案 2 :(得分:1)

您的模型类可以实现IValidatableObject接口。

通过这种方式,您可以访问模型类的所有属性,并可以执行所有自定义验证。

您还有IClientValidatable接口,用于客户端验证,但我不确定是否直接在模型类中实现它,MVC会选择客户端验证,因为我只使用此接口来指定自定义验证属性中的客户端验证。

答案 3 :(得分:1)

我也有类似的情况,我需要将属性A的值与属性B进行比较,并通过以下方式完成:

 public sealed class PropertyAAttribute : ValidationAttribute
{
    public string propertyBProperty { get; set; }
    // Override the isValid function
    public override bool IsValid(object value)
    {
         // Do your comparison here, eg:
          return A >= B;
    }
}

然后只需使用自定义验证属性:

 [PropertyA(propertyBProperty = "PropertyB")]
 public string Property A {get; set;}

我也非常努力并从别人那里得到这个解决方案,希望这有帮助!

相关问题