Iam尝试根据复选框值验证文本框。请查看我的模型类和IsValid覆盖方法。
14-40
您可以在public class Product
{
//Below property value(HaveExperiance)
[MustBeProductEntered(HaveExperiance)]
public string ProductName { get; set; }
public bool HaveExperiance { get; set; }
}
public class MustBeTrueAttribute : ValidationAttribute
{
//Here i need the value of HaveExperiance property which
//i passed from [MustBeProductEntered(HaveExperiance)] in product class above.
public override bool IsValid(object value)
{
return value is bool && (bool)value;
}
}
类中的ProductName
属性中看到iam尝试传递product
类属性值,如果已检查,则用户必须填写HaveExperiance
} 文本框。
所以我的原始问题是如何根据ProductName
值验证ProductName
文本框,提前感谢。
修改
HaveExperiance
控制器
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace Mvc.Affiliates.Models
{
public class MyProducts
{
[Key]
[Required(ErrorMessage = "Please insert product id.")]
public string ProductId { get; set; }
[RequiredIf("HaveExperiance")]
public string ProductName { get; set; }
public bool HaveExperiance { get; set; }
public List<MyProducts> prolist { get; set; }
}
public class RequiredIfAttribute : ValidationAttribute
{
private RequiredAttribute _innerAttribute = new RequiredAttribute();
public string Property { get; set; }
public object Value { get; set; }
public RequiredIfAttribute(string typeProperty)
{
Property = typeProperty;
}
public RequiredIfAttribute(string typeProperty, object value)
{
Property = typeProperty;
Value = value;
}
public override bool IsValid(object value)
{
return _innerAttribute.IsValid(value);
}
}
public class RequiredIfValidator : DataAnnotationsModelValidator<RequiredIfAttribute>
{
public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute) : base(metadata, context, attribute) { }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return base.GetClientValidationRules();
}
public override IEnumerable<ModelValidationResult> Validate(object container)
{
PropertyInfo field = Metadata.ContainerType.GetProperty(Attribute.Property);
if (field != null)
{
var value = field.GetValue(container, null);
if ((value != null && Attribute.Value == null) || (value != null && value.Equals(Attribute.Value)))
{
if (!Attribute.IsValid(Metadata.Model))
{
yield return new ModelValidationResult { Message = ErrorMessage };
}
}
}
}
}
查看
public class HomeController : Controller
{
//
// GET: /Home/
MvcDbContext _db = new MvcDbContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MyProducts model)
{
string ProductId = model.ProductId;
string ProductName = model.ProductName;
//bool remember = model.HaveExperiance;
return View();
}
}
到目前为止,我已经尝试了上面的代码,实际上当我点击复选框时我需要它然后它应该开始验证我的ProductName文本框,如果取消选中则不然。我在上面的代码中遗漏了一件小事,请帮助并纠正我。
答案 0 :(得分:5)
这是如何基于另一个属性创建自定义验证属性的完整示例:
public class RequiredIfAttribute : ValidationAttribute
{
private RequiredAttribute _innerAttribute = new RequiredAttribute();
public string Property { get; set; }
public object Value { get; set; }
public RequiredIfAttribute(string typeProperty) {
Property = typeProperty;
}
public RequiredIfAttribute(string typeProperty, object value)
{
Property = typeProperty;
Value = value;
}
public override bool IsValid(object value)
{
return _innerAttribute.IsValid(value);
}
}
public class RequiredIfValidator : DataAnnotationsModelValidator<RequiredIfAttribute>
{
public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute) : base(metadata, context, attribute) { }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return base.GetClientValidationRules();
}
public override IEnumerable<ModelValidationResult> Validate(object container)
{
PropertyInfo field = Metadata.ContainerType.GetProperty(Attribute.Property);
if (field != null) {
var value = field.GetValue(container, null);
if ((value != null && Attribute.Value == null) || (value != null && value.Equals(Attribute.Value))) {
if (!Attribute.IsValid(Metadata.Model)) {
yield return new ModelValidationResult { Message = ErrorMessage };
}
}
}
}
}
在Global.asax
的{{1}}文件中添加此部分:
Application_Start
此部分需要注册DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredIfValidator));
,否则MVC将仅使用RequiredIfValidator
忽略RequiredIfAttribute
。
如果您想验证RequiredIfValidator
ProductName
是否有值:
HaveExperiance
如果您希望仅在[RequiredIf("HaveExperiance")]
public string ProductName { get; set; }
为false时验证ProductName
:
HaveExperiance
如果您想仅在[RequiredIf("HaveExperiance", false)]
public string ProductName { get; set; }
为真时验证ProductName
:
HaveExperiance
在[RequiredIf("HaveExperiance", true)]
public string ProductName { get; set; }
类中,我创建了一个RequiredIfAttribute
对象,仅用于验证传递给RequiredAttribute
方法的值。
IsValid
字段用于保存激活验证的属性名称。它在类Property
中用于使用反射(RequiredIfValidator
)获取字段当前值。
当您在代码中调用验证时(例如,当您执行field.GetValue(container, null)
时),首先调用if(TryValidateModel(model))
类,然后调用RequiredIfValidator
(通过RequiredIfAttribute
)类,如果有的话条件有效(Attribute.IsValid(Metadata.Model)
)。
最后一件事。由于(value != null && Attribute.Value == null) || (value != null && value.Equals(Attribute.Value))
继承自RequiredIfAttribute
,因此您也可以使用与任何其他验证属性相同的错误消息。
ValidationAttribute