asp.net-mvc-3 – 如何在ASP .NET MVC 3中验证与另一个值相关的
发布时间:2020-12-15 23:20:31 所属栏目:asp.Net 来源:网络整理
导读:我有两个字段有些电话号码和手机号码.就像是.. [Required] public string Phone { get; set; } [Required] public string Mobile{ get; set; } 但用户可以在其中任何一个中输入数据.一个是强制性的如何处理它们,即当用户在另一个字段中输入数据时,如何禁用一
|
我有两个字段有些电话号码和手机号码.就像是..
[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而不是数据注释来对我的模型执行验证.实现这样简单的验证场景是以简单的方式来实现的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-core – 实体框架核心 – 相当于IN子句
- ASP.Net 3.5 / 4.0 CodeBehind还是CodeFile?
- asp.net-mvc – 在ASP.NET MVC中实现“记住我”功能
- asp.net-mvc – 避免在业务层(MVC 3)中使用SelectList
- asp.net-mvc – 在foreach中的mvc radiobuttons
- asp.net-core – 带有JSONP的ASP.NET Core MVC
- Exp5 MSF基础应用 20164320 王浩
- 单元测试传统ASP.NET Webforms应用程序
- asp.net – 如何在Kendo UI中获取下拉菜单的选定项目的文本
- 经典ASP错误’80020009’发生异常
推荐文章
站长推荐
- asp.net-mvc – 可以将NUnit集成到Visual Studio
- asp.net – 配置示例
- asp.net – 未捕获TypeError:无法读取未定义的属
- 使用ASP.NET和C#在DropDownList中选择多个值
- I can 前端-07 ASP.NET 常用对象
- asp.net – 我可以信任从ServerVariables [“REM
- asp.net – 查找和删除孤立的网页,图像和其他相关
- asp.net-mvc – 资源解释为Document但使用MIME类
- ASP.Net/web.config – “条目’x’已经输入”?
- asp.net – .NET 4.5 WebForms:我(仍然)真的必须
热点阅读
