gpt4 book ai didi

Asp.Net MVC 验证 - 依赖字段

转载 作者:行者123 更新时间:2023-12-04 10:22:07 25 4
gpt4 key购买 nike

我目前正在尝试通过 MVC 验证工作,并且遇到了一些问题,根据另一个字段的值需要一个字段。下面是一个例子(我还没有弄清楚) - 如果 PaymentMethod == "Cheque",那么 ChequeName 应该是必需的,否则它可以通过。

[Required(ErrorMessage = "Payment Method must be selected")]
public override string PaymentMethod
{ get; set; }

[Required(ErrorMessage = "ChequeName is required")]
public override string ChequeName
{ get; set; }

我正在为 [Required] 使用 System.ComponentModel.DataAnnotations,并且还扩展了 ValidationAttribute 以尝试使其正常工作,但我无法传递变量来进行验证(下面的扩展)
public class JEPaymentDetailRequired : ValidationAttribute 
{
public string PaymentSelected { get; set; }
public string PaymentType { get; set; }

public override bool IsValid(object value)
{
if (PaymentSelected != PaymentType)
return true;
var stringDetail = (string) value;
if (stringDetail.Length == 0)
return false;
return true;
}
}

执行:
[JEPaymentDetailRequired(PaymentSelected = PaymentMethod, PaymentType = "Cheque", ErrorMessage = "Cheque name must be completed when payment type of cheque")]

有没有人有过这种验证的经验?将它写入 Controller 会更好吗?

谢谢你的帮助。

最佳答案

如果除了服务器上的模型验证之外,还需要客户端验证,我认为最好的方法是自定义验证属性(如 Jaroslaw 建议的那样)。我在这里包括我使用的来源。

自定义属性:

public class RequiredIfAttribute : DependentPropertyAttribute
{
private readonly RequiredAttribute innerAttribute = new RequiredAttribute();

public object TargetValue { get; set; }


public RequiredIfAttribute(string dependentProperty, object targetValue) : base(dependentProperty)
{
TargetValue = targetValue;
}


protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);

if (field != null)
{
// get the value of the dependent property
var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

// compare the value against the target value
if ((dependentvalue == null && TargetValue == null) ||
(dependentvalue != null && dependentvalue.Equals(TargetValue)))
{
// match => means we should try validating this field
if (!innerAttribute.IsValid(value))
// validation failed - return an error
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}

return ValidationResult.Success;
}

public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif"
};

var depProp = BuildDependentPropertyId(DependentProperty, metadata, context as ViewContext);

// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
var targetValue = (TargetValue ?? "").ToString();
if (TargetValue != null)
if (TargetValue is bool)
targetValue = targetValue.ToLower();

rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);

yield return rule;
}
}

Jquery 验证扩展:
$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'targetvalue'], function (options) {
options.rules['requiredif'] = {
dependentproperty: options.params['dependentproperty'],
targetvalue: options.params['targetvalue']
};
options.messages['requiredif'] = options.message;
});

$.validator.addMethod('requiredif',
function (value, element, parameters) {
var id = '#' + parameters['dependentproperty'];

// get the target value (as a string,
// as that's what actual value will be)
var targetvalue = parameters['targetvalue'];
targetvalue = (targetvalue == null ? '' : targetvalue).toString();

// get the actual value of the target control
var actualvalue = getControlValue(id);

// if the condition is true, reuse the existing
// required field validator functionality
if (targetvalue === actualvalue) {
return $.validator.methods.required.call(this, value, element, parameters);
}

return true;
}
);

用属性装饰一个属性:
[Required]
public bool IsEmailGiftCertificate { get; set; }

[RequiredIf("IsEmailGiftCertificate", true, ErrorMessage = "Please provide Your Email.")]
public string YourEmail { get; set; }

关于Asp.Net MVC 验证 - 依赖字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2009776/

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