我有两个字段有些电话号码和手机号码.就像是..
[required] public string Phone { get; set; } [required] public string Mobile{ get; set; }
但用户可以在其中任何一个中输入数据.一个是强制性的如何处理它们,即当用户在另一个字段中输入数据时,如何禁用一个字段所需的字段验证器.在哪种情况下,我必须在javascript中处理它,我需要添加什么脚本.任何人都可以帮忙找到解决方案
解决方法
一种可能性是编写自定义验证属性:
public class requiredIfOtherFieldIsNullAttribute : ValidationAttribute,IClientValidatable { private readonly string _otherProperty; public requiredIfOtherFieldIsNullAttribute(string otherProperty) { _otherProperty = otherProperty; } protected override ValidationResult IsValid(object value,ValidationContext validationContext) { var property = validationContext.ObjectType.GetProperty(_otherProperty); if (property == null) { return new ValidationResult(string.Format( CultureInfo.CurrentCulture,"Unknown property {0}",new[] { _otherProperty } )); } var otherPropertyValue = property.GetValue(validationContext.ObjectInstance,null); if (otherPropertyValue == null || otherPropertyValue as string == string.Empty) { if (value == null || value as string == string.Empty) { return new ValidationResult(string.Format( CultureInfo.CurrentCulture,FormatErrorMessage(validationContext.DisplayName),new[] { _otherProperty } )); } } return null; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata Metadata,ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(Metadata.GetDisplayName()),ValidationType = "requiredif",}; rule.ValidationParameters.Add("other",_otherProperty); yield return rule; } }
您将应用于您的视图模型的其中一个属性:
public class Myviewmodel { [requiredIfOtherFieldIsNull("Mobile")] public string Phone { get; set; } public string Mobile { get; set; } }
那么你可以有一个控制器:
public class HomeController : Controller { public ActionResult Index() { return View(new Myviewmodel()); } [HttpPost] public ActionResult Index(Myviewmodel model) { return View(model); } }
最后,您将注册一个适配器来连接此自定义规则的客户端验证的视图:
@model Myviewmodel <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> <script type="text/javascript"> jQuery.validator.unobtrusive.adapters.add( 'requiredif',['other'],function (options) { var getModelPrefix = function (fieldName) { return fieldName.substr(0,fieldName.lastIndexOf('.') + 1); } var appendModelPrefix = function (value,prefix) { if (value.indexOf('*.') === 0) { value = value.replace('*.',prefix); } return value; } var prefix = getModelPrefix(options.element.name),other = options.params.other,fullOtherName = appendModelPrefix(other,prefix),element = $(options.form).find(':input[name="' + fullOtherName + '"]')[0]; options.rules['requiredif'] = element; if (options.message) { options.messages['requiredif'] = options.message; } } ); jQuery.validator.addMethod('requiredif',function (value,element,params) { var otherValue = $(params).val(); if (otherValue != null && otherValue != '') { return true; } return value != null && value != ''; },''); </script> @using (Html.BeginForm()) { <div> @Html.LabelFor(x => x.Phone) @Html.EditorFor(x => x.Phone) @Html.ValidationMessageFor(x => x.Phone) </div> <div> @Html.LabelFor(x => x.Mobile) @Html.EditorFor(x => x.Mobile) @Html.ValidationMessageFor(x => x.Mobile) </div> <button type="submit">OK</button> }
相当生病的东西,非常容易,因为我们在日常生活中遇到的验证规则.我不知道ASP.NET MVC的设计者在决定选择一种声明式的验证方法而不是强制性时,一直在想什么.
无论如何,这就是为什么我使用FluentValidation.NET而不是数据注释来对我的模型执行验证.实现这样简单的验证场景是以简单的方式来实现的.