gpt4 book ai didi

asp.net-mvc-3 - requiredIf 条件验证属性

转载 作者:行者123 更新时间:2023-12-03 05:53:14 24 4
gpt4 key购买 nike

我正在寻找一些有关实现执行以下操作的验证属性的最佳方法的建议。

型号

public class MyInputModel 
{
[Required]
public int Id {get;set;}

public string MyProperty1 {get;set;}
public string MyProperty2 {get;set;}
public bool MyProperty3 {get;set;}

}

我想要至少 prop1 prop2 prop3 具有一个值,并且如果 prop3 是填充它的唯一值,则它不应该等于 false。我将如何为此编写验证属性?

感谢您的帮助!

最佳答案

我昨天遇到了同样的问题,但我以一种非常干净的方式完成了它,该方式适用于客户端和服务器端验证。

条件:根据模型中其他属性的值,您希望将另一个属性设为必需。这是代码:

public class RequiredIfAttribute : RequiredAttribute
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }

public RequiredIfAttribute(String propertyName, Object desiredvalue)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
}

protected override ValidationResult IsValid(object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
Type type = instance.GetType();
Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
if (proprtyvalue.ToString() == DesiredValue.ToString())
{
ValidationResult result = base.IsValid(value, context);
return result;
}
return ValidationResult.Success;
}
}

PropertyName 是您要为其设置条件的属性
DesiredValue 是 PropertyName(属性)的特定值,必须验证您的其他属性是否为必需

假设您有以下内容:

public enum UserType
{
Admin,
Regular
}

public class User
{
public UserType UserType {get;set;}

[RequiredIf("UserType",UserType.Admin,
ErrorMessageResourceName="PasswordRequired",
ErrorMessageResourceType = typeof(ResourceString))]
public string Password { get; set; }
}

最后但并非最不重要的一点是,为您的属性注册适配器,以便它可以进行客户端验证(我将其放在 global.asax, Application_Start 中)

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),
typeof(RequiredAttributeAdapter));

已编辑

有些人报告了客户端无论如何都会触发或不起作用的问题。因此,我修改了上面的代码,以使用 Javascript 进行条件客户端验证。对于这种情况,您不需要注册适配器

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }
private readonly RequiredAttribute _innerAttribute;

public RequiredIfAttribute(String propertyName, Object desiredvalue)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
_innerAttribute = new RequiredAttribute();
}

protected override ValidationResult IsValid(object value, ValidationContext context)
{
var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

if (dependentValue.ToString() == DesiredValue.ToString())
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
}
}
return ValidationResult.Success;
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredif",
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

yield return rule;
}
}

最后是 javascript(将其捆绑并渲染...将其放入自己的脚本文件中)

$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
options.rules['requiredif'] = options.params;
options.messages['requiredif'] = options.message;
});

$.validator.addMethod('requiredif', function (value, element, parameters) {
var desiredvalue = parameters.desiredvalue;
desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
var actualvalue = {}
if (controlType == "checkbox" || controlType == "radio") {
var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
actualvalue = control.val();
} else {
actualvalue = $("#" + parameters.dependentproperty).val();
}
if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
var isValid = $.validator.methods.required.call(this, value, element, parameters);
return isValid;
}
return true;
});

显然,您需要根据要求包含不显眼的验证 jQuery

关于asp.net-mvc-3 - requiredIf 条件验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7390902/

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