- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在寻找一些有关实现执行以下操作的验证属性的最佳方法的建议。
型号
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/
我正在使用 JaroslawWaliszko 的 ExpressiveAnnotations .当我通过 ModelState.IsValid 检查服务器端时,它工作正常。但它没有显示客户端验证消息。
如果启用了功能(如果您选择了复选框),我试图让一个字段成为必填字段。但是该验证不会通过单击选择/取消选择复选框来触发 Enable Vue.js validations: {
我有一个带有两个单选按钮的 asp.net MVC 4 View 。在页面加载时, View 的一部分使用 css 隐藏。在 View 本身上,当用户选择一个单选按钮时,一旦隐藏部分并显示其他部分,当
我们正在尝试使用 Foolproof 验证注释 [RequiredIf] 来检查是否需要电子邮件地址。我们还创建了一个枚举以避免在 ViewModel 中使用查找表 ID。代码如下所示: public
我正在开发一个 Laravel 5.8 项目,并尝试显示使用 requiredIf 验证规则的验证的自定义验证消息。 这是我的设置方法: $validation = Validator::make(
我正在寻找一些有关实现执行以下操作的验证属性的最佳方法的建议。 型号 public class MyInputModel { [Required] public int Id {get
我希望我的validation.xml 仅在从下拉列表中选择某些选项时检查是否为空。到目前为止我已经 field[0]
我正在尝试有条件地验证 MVC.NET Core 中的字段。我有两个单选按钮。如果我选择是(对于所有权),我想在下方创建一个必填字段(事件下拉列表) 但是,无论我多么努力,要验证的值始终来自 Acti
我的应用程序有一个要求,在某些条件下需要一个字段,然后该字段应该与特定模式匹配。有没有办法可以将所需的 if 和 mask 条件结合起来?我使用的是struts 1。 这是validation.xml
我有以下场景:多个必需的 DataAnnotation 属性。我制作了一个自定义标签助手,它在需要装饰的属性旁边呈现一个“*”。现在,在客户端,如果依赖属性更改值,我希望能够隐藏/显示。 为了更精确的
我正在使用custom RequiredIf attribute created by Simon Ince在我的 MVC 应用程序中。 我有一个 View 模型,它像这样传递给 View : pub
如何在 .NET Core 中实现 RequiredIf 条件操作以进行基于模型的验证。 在 ASP.NET MVC 中,曾与 ExpressiveAnnotation 包一起使用,但它不适用于 .N
如何在 .NET Core 中实现 RequiredIf 条件操作以进行基于模型的验证。 在 ASP.NET MVC 中,曾与 ExpressiveAnnotation 包一起使用,但它不适用于 .N
我是一名优秀的程序员,十分优秀!