gpt4 book ai didi

asp.net-mvc - MVC 不显眼的验证 - 依赖于先前选择的自定义验证器

转载 作者:行者123 更新时间:2023-12-01 23:05:45 24 4
gpt4 key购买 nike

我有一个包含多个字段的标准地址表格。例如

  • 地址行 1
  • 地址第 2 行
  • 国家
  • 国家
  • 邮政编码

  • 问题是只有当“国家”设置为美国时,“州”字段才应该是必填字段。如果国家/地区设置为其他任何内容,则不需要它。我可以在 Controller 中处理它,但我想在客户端不显眼地进行处理。有什么建议?

    最佳答案

    刚刚根据您的要求编写了一个快速演示。

    // model
    public class Address
    {
    public int Id { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }

    [Required]
    public string Country { get; set; }

    [RequiredIfCountryIsUSA]
    public string State { get; set; }
    public string PostCode { get; set; }
    }


    // Validation Attribute
    public class RequiredIfCountryIsUSA : ValidationAttribute, IClientValidatable
    {
    public RequiredIfCountryIsUSA()
    {

    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
    var countryPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty("Country");
    var countryValue = countryPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString();
    if (countryValue == "USA" && (value == null || string.IsNullOrEmpty(value.ToString().Trim())))
    {
    return new ValidationResult("State is required when Country is USA");
    }

    return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
    var rule = new ModelClientValidationRule();
    rule.ErrorMessage = "State is required when country is USA";
    rule.ValidationParameters.Add("country", "USA");
    rule.ValidationType = "iscountryusa";

    yield return rule;
    }
    }

    客户端javascript
    (function ($) {
    $.validator.addMethod("iscountryusa", function (state, element, country) {
    var country = $('#Country').val();

    if (country == 'USA' && state == '') {
    return false;
    }

    return true;
    });

    $.validator.unobtrusive.adapters.addSingleVal("iscountryusa", "country");
    } (jQuery));

    关于asp.net-mvc - MVC 不显眼的验证 - 依赖于先前选择的自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23952907/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com