【问题标题】:How to validate textbox based on checkbox value如何根据复选框值验证文本框
【发布时间】:2016-01-27 07:25:34
【问题描述】:

我正在尝试根据复选框值验证文本框。请查看我的模型类和 IsValid 覆盖方法。

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

您可以在上面的product 类中的ProductName 属性中看到我正在尝试传递HaveExperiance 类属性值,如果选中,则用户必须填写ProductName 文本框。

所以我最初的问题是,如何根据 HaveExperiance 值验证 ProductName 文本框,提前致谢。

编辑:

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

查看

@model   Mvc.Affiliates.Models.MyProducts
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Details</h2>
<br />

<div style="height:200px; width:100%">
  @using  (Html.BeginForm("Index","Home", FormMethod.Post))
    {

   <h2>Details</h2>

        @Html.LabelFor(model => model.ProductId)
        @Html.TextBoxFor(model => model.ProductId)

        @Html.LabelFor(model => model.ProductName)
        @Html.EditorFor(model => model.ProductName)
        @Html.ValidationMessageFor(model => model.ProductName, "*")

        @Html.CheckBoxFor(model => model.HaveExperiance)
        @Html.ValidationMessageFor(model => model.HaveExperiance, "*")
       <input type="submit" value="Submit" />
  }

</div>

到目前为止,我已经尝试了上面的代码,实际上我需要当我单击复选框时,它应该开始验证我的 ProductName 文本框,如果取消选中则不是。我在上面的代码中遗漏了一点东西,请帮助并纠正我。

【问题讨论】:

  • 建议您使用foolproof [RequiredIfTrue] 或类似的验证属性。但是如果你想自己写,那么this article 是一个很好的起点

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

这是一个如何基于另一个属性创建自定义验证属性的完整示例:

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文件Application_Start中添加这部分:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredIfValidator));

这部分是注册RequiredIfValidator所必需的,否则MVC将只使用RequiredIfAttribute而忽略RequiredIfValidator

如果你想验证ProductName 是否HaveExperiance 有一个值:

[RequiredIf("HaveExperiance")]
public string ProductName { get; set; }

如果您想仅在 HaveExperiance 为 false 时验证 ProductName

[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 &amp;&amp; Attribute.Value == null) || (value != null &amp;&amp; value.Equals(Attribute.Value))) .

最后一件事。因为RequiredIfAttribute 继承自ValidationAttribute,所以您也可以像使用任何其他验证属性一样使用错误消息。

[RequiredIf("HaveExperiance", true, ErrorMessage = "The error message")]
public string ProductName { get; set; }

[RequiredIf("HaveExperiance", true, ErrorMessageResourceName = "ResourceName", ErrorMessageResourceType = typeof(YourResourceType))]
public string ProductName { get; set; }

【讨论】:

  • 如果你也添加一些解释会很棒
  • @ArijitMukherjee 我希望现在好多了:-)
  • 太好了,是的,现在对每个人都有帮助
  • 感谢您的回复,您的示例看起来很酷,今天将运行并响应,感谢您的详细解释。
  • @erikscandola 我试过你的代码。请参阅编辑:我的原始问题中的代码,请帮助纠正我缺少的内容?,谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多