ASP.NET 不显眼的 MVC 自定义验证

ASP.NET MVC Custom Validation with Unobtrusive

我正在使用 ASP.NET MVC 和 Unobtrusive js,它 运行 非常好,但我想为这样的事情设置验证规则:

我的下拉列表有两个值 "Yes" 和 "No"。我也有一个文本框。

基于从下拉列表中选择的值 if

"Yes" 我想在客户端和服务器端使用 Unobtrusive 验证是否输入了文本框值,如果

"No" 没有验证应该起作用我的意思是如果文本框值为空或输入的任何值都可以,因为如果下拉列表值为否,我不想存储该值没有验证应该对该文本框起作用.

请有人帮我解决这个问题。

我已经提到了很多 Whosebug 问题和答案,那里的答案也很好,但我无法将它们放在一起来获得我的解决方案。

我在 bool 中得到了下拉选择的值,即

 public bool IsTestUnit { get; set; }
    [RequiredIfUniTestIsYes("IsTestUnit == true", true, ErrorMessage = "Please Enter Test Unit Job Order Number ")]
        public long TestUnitJobOrder { get; set; }

我试过的代码:

 public class RequiredIfUniTestIsYes : ValidationAttribute, IClientValidatable
    {
        public RequiredIfUniTestIsYes()
        {

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var countryPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty("IsTestUnit");
            var countryValue = countryPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString();
            if (countryValue == "True" && (value.ToString().Trim() == "" || Convert.ToInt32(value) == 0))
            {
                return new ValidationResult("Please Enter Unit Test Job Order Number");
            }

            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = "Please Enter Unit Test Job Order Number";
            rule.ValidationParameters.Add("istestunit", "true");
            rule.ValidationType = "isunittest";

            yield return rule;
        }
    }

Javascript:

$.validator.addMethod("isunittest", function (state, element, country) {
                 var country = $('#WorkOderDetailViewModel_IsTestUnit').val();
                     if (country == 'True' && state == '') {
                         return false;
                     }
                     return true;
                 });

             $.validator.unobtrusive.adapters.addSingleVal("isunittest", "true");

             (function ($) {
                 $.validator.addMethod('customRequire', function (value, element) {
                     // your validation logic here
                     return true; // true if valid, otherwise false 
                 });
                 $.validator.unobtrusive.adapters.add('customRequire');
             })(jQuery);

我只是复制粘贴代码,并没有更改名称,所以请忽略这些错误。

鉴于您呈现如下字段:

@Html.DropDownListFor(m => m.IsTestUnit,
new[] { true, false }.Select(b => new SelectListItem { Text = b ? "Yes" : "No", Value = b.ToString().ToLower() }),
new { id = "WorkOderDetailViewModel_IsTestUnit" })

@Html.TextBoxFor(m => m.TestUnitJobOrder)
@Html.ValidationMessageFor(m => m.TestUnitJobOrder)

模型属性声明为:

    public bool IsTestUnit { get; set; }

    [RequiredIfUniTestIsYes("IsTestUnit", ErrorMessage = "Please Enter Test Unit Job Order Number ")]
    public long? TestUnitJobOrder { get; set; }

您可以像这样定义自定义验证器:

public class RequiredIfUniTestIsYes : ValidationAttribute, IClientValidatable
{
    private string _dependency;

    public RequiredIfUniTestIsYes(string dependency)
    {
        _dependency = dependency;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var countryPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(_dependency);
        var countryValue = (bool)countryPropertyInfo.GetValue(validationContext.ObjectInstance, null);
        var number = default(long);
        if (countryValue && (value == null || !long.TryParse(value.ToString(), out number)))
        {
            return new ValidationResult("Please Enter Unit Test Job Order Number");
        }

        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = "Please Enter Unit Test Job Order Number";
        rule.ValidationParameters.Add("istestunit", "true");
        rule.ValidationType = "isunittest";

        yield return rule;
    }
}

并像这样注册客户端非侵入式验证:

    $.validator.unobtrusive.adapters.add("isunittest", ['istestunit'], function(options){
        options.rules['isunittest'] = options.params;
        options.messages['isunittest'] = options.message;
    });    
    $.validator.addMethod('isunittest', function (state, element, params) {
        var country = $('#WorkOderDetailViewModel_IsTestUnit').val();
        if (country == 'true' && state == '') {
            return false;
        }
        return true;
    });