English 中文(简体)
MVC 3 认证模型
原标题:MVC 3 Complicated validation of models

目前在MVC 3中使用的验证方法是ValidationAttributes。 我有一个与这一模式非常具体、在几个特性之间具有互动关系的分类验证。

基本来说,该模型收集了其他模型,所有模型都以同样的形式编辑。 让我们称之为《示范公约》,并收集《示范公约》。 我可能必须证实的是,《示范公约》的某些财产总额减去《示范法》中的财产。 用户数分数可分为几种选择。

审定 补助金非常笼统,我不敢肯定他们适合从事这项工作。

我不知道IDateErrorInfo是如何在3号MVC中得到支持的,以及它是否直接从箱子中运作。

One way would be to validate through a method but that means I can t do a clientside validation.

采取什么适当方式这样做? 我是否还有其他选择? 我低估了ValidationAttribute的力量?

最佳回答

IDateErrorInfo

IDateErrorInfo得到MVC框架的支持(见here)。 缺省模型约束器将可重新计算模型目标,使html成为模型的要素。 如果模型约束器发现模型采用接口,则该模型将采用接口方法验证模型中的每一财产或验证整个模型。 See the tutorial for more information.

如果你想使用这种方法(引用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>

然后可以用来启动已经确定的任何客户方验证。 下面举例说明如何界定客户的证明。

<>>Explicit Validation

如你所述,你可以明确确认行动模式。 例如:

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.Validation Summary来显示错误信息,因为上述代码会增加一个模型级错误,而不是一个财产等级错误。

2. 具体指明财产等级错误,请说明:

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

当时认为使用:

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

显示错误信息。

同样,任何客户方验证都需要通过确定财产的方式,在客户方验证中进行人工链接。

www.un.org/Depts/DGACM/index_spanish.htm 关税同盟

如果我正确理解这个问题,你就试图验证一个包含单一价值和收集财产并汇出的模型。

例如,我将向用户介绍一个最高价值领域和5个价值领域。 最大价值领域将是模型的一个单一价值,因为5个价值领域将成为收集的一部分。 审定将确保价值领域的总和不超过最高价值领域。 鉴定将定义为模型的属性,该模型还将在冰理上与 j印客户的同价挂钩。

@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"/>
}

I have not added any validation against the value fields as I do not want to overcomplicate the example.

<>《示范法》:

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.
    }
}

http://www.un.org。

The [Values Must notExceedTotal] Depende defined on the model can be defined by over the ValidationAttribute category:

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;
    }
}

http://www.un.org/Depts/DGACM/index_french.htm

To add client side validation to this attribute it would need to implement the IClientValidatable interface:

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="" />

尤其注意到<代码>数据-val- Valuesmustnotexceed Total的验证属性。 这就是我们的客户方验证将如何与验证归属联系起来。

Adding Client Side Validation:

添加客户方面的验证,你需要在意见的标语中添加以下类似的图书馆参考资料:

<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>

你们还需要确保客户一方的验证在网上转换。 尽管我认为这应该不成事实:

<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>

And that should be it. I m sure that there are improvements that can be made here and there and that if i ve misunderstood the problem slightly that you should be able to tweak the validation for your needs. But I believe this validation seems to be the way that most developers code custom attributes including more complex client side validation.

希望这一帮助。 让我知道,你是否对上述问题提出任何问题或建议。

问题回答

我也想到一些类似的情况,我需要将财产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;}

I also tried very hard and get this solution from others, Hope this help!

您的模范班子可以实施

这样,你就能够接触到你模式类别的所有特性,并且能够进行您的所有习俗验证。

http://msdn.microsoft.com/en-us/library/system.web.mvc.iclientvalidatable%28VS.9829.aspx'rel=“nofollow”>IClientValidatable 接口,供客户方验证,但我不清楚的是,通过在模型类别中直接实施,客户验证是由MVC挑选的,因为我只利用这个接口来在验证客户。





相关问题
Bind Button.IsEnabled to custom validation with XAML?

I am sorry I didn t know how to title my question any better, you name it if you got a good 1. I have an entity Contact. this person has navigation properties: Address, Phones (A collection of Phone)....

WPF - MVVM - NHibernate Validation

Im facing a bit of an issue when trying to validate a decimal property on domain object which is bound to a textbox on the view through the viewmodel. I am using NHibernate to decorate my property on ...

Wpf Combobox Limit to List

We are using Wpf Combobox to allow the user to do the following things: 1) select items by typing in the first few characters 2) auto complete the entry by filtering the list 3) suggesting the first ...

Rails 101 | validates_currency?

I ve searched high and low, but I could not find a solution, to what I think seems like a very common task. In a form I want to have a text input that accepts currency strings (i.e. $1,000,000 or ...

CodeIgniter form verification and class

I m using the form validation library and have something like this in the view <p> <label for="NAME">Name <span class="required">*</span></label> <?...

热门标签