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.
希望这一帮助。 让我知道,你是否对上述问题提出任何问题或建议。