如何根据复选框值验证文本框

劳夫·阿比德(Rauf Abid)

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

您可以在上面的类的ProductName属性中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();
        }
    }

看法

@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文本框,如果取消选中则不行。我在上面的代码中缺少一点东西,请帮助纠正我。

埃里斯坎多拉

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

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

如果您只想验证ProductName是否HaveExperiance为false:

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

如果只想验证ProductName是否HaveExperiance为true:

[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))

最后一件事。因为RequiredIfAttributeValidationAttribute那里继承,您也可以使用错误消息,就像使用其他任何验证属性一样。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何从复选框更改文本框值

来自分类Dev

MVC-如何根据在同一视图文本框中输入的值设置复选框的显示名称

来自分类Dev

根据复选框显示/隐藏文本框

来自分类Dev

jQuery复选框和文本框验证

来自分类Dev

单击事件后如何更改文本框,选择框和复选框的值?

来自分类Dev

选中复选框时如何禁用文本框并使用纯JavaScript清除值

来自分类Dev

选中复选框时如何禁用文本框并使用纯JavaScript清除值

来自分类Dev

当复选框被选中或复选框未选中删除值时,如何在另一个文本框中获得复选框值和文本框值的总和

来自分类Dev

C#根据运行时文本框用户输入值禁用复选框

来自分类Dev

单击复选框,将选中的值放入文本框,然后从文本框中删除未选中的值

来自分类Dev

验证2个复选框和2个文本框

来自分类Dev

如果选中复选框,则更改文本框文本

来自分类Dev

如果文本框有文本,则标记复选框

来自分类Dev

jQuery总和使用复选框值和文本框值

来自分类Dev

如何使用(搜索文本框)查找复选框的文本?

来自分类Dev

获取文本框中所有选定复选框的值

来自分类Dev

获取复选框总计数并在文本框中保存值(如果选中)

来自分类Dev

使用PHP和MySQL提交多个复选框以及文本框输入值?

来自分类Dev

复选框更改时添加/删除文本框值

来自分类Dev

jQuery-选中复选框时获取文本框的上一个值

来自分类Dev

获取表中每一行的文本框和复选框值

来自分类Dev

选中复选框时,文本框值上的jQuery函数更改

来自分类Dev

复选框更改时添加/删除文本框值

来自分类Dev

获取复选框总计数并在文本框中保存值(如果选中)

来自分类Dev

使用复选框启用文本框

来自分类Dev

复选框显示/隐藏文本框WPF

来自分类Dev

动态复选框以启用文本框

来自分类Dev

单击复选框动态隐藏/显示文本框

来自分类Dev

基于文本框的标记/取消标记复选框

Related 相关文章

  1. 1

    如何从复选框更改文本框值

  2. 2

    MVC-如何根据在同一视图文本框中输入的值设置复选框的显示名称

  3. 3

    根据复选框显示/隐藏文本框

  4. 4

    jQuery复选框和文本框验证

  5. 5

    单击事件后如何更改文本框,选择框和复选框的值?

  6. 6

    选中复选框时如何禁用文本框并使用纯JavaScript清除值

  7. 7

    选中复选框时如何禁用文本框并使用纯JavaScript清除值

  8. 8

    当复选框被选中或复选框未选中删除值时,如何在另一个文本框中获得复选框值和文本框值的总和

  9. 9

    C#根据运行时文本框用户输入值禁用复选框

  10. 10

    单击复选框,将选中的值放入文本框,然后从文本框中删除未选中的值

  11. 11

    验证2个复选框和2个文本框

  12. 12

    如果选中复选框,则更改文本框文本

  13. 13

    如果文本框有文本,则标记复选框

  14. 14

    jQuery总和使用复选框值和文本框值

  15. 15

    如何使用(搜索文本框)查找复选框的文本?

  16. 16

    获取文本框中所有选定复选框的值

  17. 17

    获取复选框总计数并在文本框中保存值(如果选中)

  18. 18

    使用PHP和MySQL提交多个复选框以及文本框输入值?

  19. 19

    复选框更改时添加/删除文本框值

  20. 20

    jQuery-选中复选框时获取文本框的上一个值

  21. 21

    获取表中每一行的文本框和复选框值

  22. 22

    选中复选框时,文本框值上的jQuery函数更改

  23. 23

    复选框更改时添加/删除文本框值

  24. 24

    获取复选框总计数并在文本框中保存值(如果选中)

  25. 25

    使用复选框启用文本框

  26. 26

    复选框显示/隐藏文本框WPF

  27. 27

    动态复选框以启用文本框

  28. 28

    单击复选框动态隐藏/显示文本框

  29. 29

    基于文本框的标记/取消标记复选框

热门标签

归档