C# 如何基于复选框值验证文本框

C# 如何基于复选框值验证文本框,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我正在尝试根据复选框值验证文本框。请查看我的模型类和IsValid重写方法 public class Product { //Below property value(HaveExperiance) [MustBeProductEntered(HaveExperiance)] public string ProductName { get; set; } public bool HaveExperiance { get; set; } } public cl

我正在尝试根据复选框值验证文本框。请查看我的模型类和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 };
                    }
                }
            }
        }
    }
查看

@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>
@model Mvc.Affiliates.Models.MyProducts
@{
ViewBag.Title=“Index”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
细节

@使用(Html.BeginForm(“Index”,“Home”,FormMethod.Post)) { 细节 @LabelFor(model=>model.ProductId) @Html.TextBoxFor(model=>model.ProductId) @Html.LabelFor(model=>model.ProductName) @Html.EditorFor(model=>model.ProductName) @Html.ValidationMessageFor(model=>model.ProductName,“*”) @CheckBoxFor(model=>model.HaveExperiance) @Html.ValidationMessageFor(model=>model.HaveExperiance,“*”) }

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

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

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 };
                }
            }
        }
    }
}
注册
RequiredIfValidator
需要此部件,否则MVC将仅使用
RequiredIfValidator
忽略
RequiredIfValidator

如果要验证
ProductName
是否
HaveExperiance
具有值:

[RequiredIf("HaveExperiance")]
public string ProductName { get; set; }
如果要仅在
HaveExperiance
为false时验证
ProductName

[RequiredIf("HaveExperiance", false)]
public string ProductName { get; set; }
如果要仅在
HaveExperiance
为true时验证
ProductName

[RequiredIf("HaveExperiance", true)]
public string ProductName { get; set; }
requirediftAttribute
class I中创建了一个
RequiredAttribute
对象,仅用于验证传递给
IsValid
方法的值

属性
字段用于保存激活验证的属性的名称。它在类
RequiredIfValidator
中使用,以使用反射获取字段当前值(
field.GetValue(container,null)

当您在代码中调用验证时(例如,当您首先调用
if(TryValidateModel(model))
),如果某些条件有效(
(value!=null&&Attribute.value==null)| |(value!=null&&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; }

建议您使用
[RequiredIfTrue]
或类似的验证属性。但是,如果您想编写自己的验证属性,那么这是一个很好的起点,如果您添加一些解释作为well@ArijitMukherjee我希望现在更好:-)太好了,是的,现在对大家都有帮助谢谢你的回复,你的例子看起来很酷,将在今天运行并响应,感谢您的详细解释。@erikscandola我已经尝试了您的代码。请参阅我原始问题中的编辑:代码,请帮助纠正我缺少的内容?谢谢。
[RequiredIf("HaveExperiance", true)]
public string ProductName { get; set; }
[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; }