我正在寻找关于实现执行以下操作的验证属性的最佳方法的一些建议.
模型
public class MyInputModel
{
[Required]
public int Id {get;set;}
public string MyProperty1 {get;set;}
public string MyProperty2 {get;set;}
public bool MyProperty3 {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我想至少使用一个值得到prop1 prop2 prop3,如果prop3是填充它的唯一值,它不应该等于false.我将如何为此编写验证属性(s?)?
谢谢你的帮助!
我得到了
参数计数不匹配
错误.它出现在该if
条款中.我的代码:
private Dictionary<string,string> ObjectToDict(Dictionary<string, string> dict, object obj)
{
var properties = obj.GetType().GetProperties();
foreach (var property in properties)
{
if (property.GetValue(obj, null) != null)
dict["{{" + property.Name + "}}"] = property.GetValue(obj, null).ToString();
}
return dict;
}
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为当我将property
值添加到字典时它可以正常工作,但是当我测试它是否null
在if
子句中时却没有.
我发现的所有问题都是在函数调用中输入了不正确数量的参数,但是AFAIK在我的两个调用之间没有什么不同.
根据各种来源设置验证后,我无法启动客户端验证方法。经过一番努力,我发现更改脚本加载的顺序可以解决问题。我提供了一个答案来显示 ASP.NET Core 3.0 MVC 的“RequiredIf”自定义属性的完整设置。希望它能节省其他人的宝贵时间。
validation client-side-validation custom-attribute unobtrusive-validation asp.net-core-3.0
在我的程序中,对于一个实体,我有一个保存和一个提交按钮。对于我的实体,我有一个字段来确定是否不需要另一个字段。这种情况的一个例子:
public class Question{
bool IsRequired {get; set;}
string Answer {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以根据 IsRequired 字段创建一个自定义验证属性来使 Answer 成为必需,但问题是,我只需要在用户“提交”表单时进行此验证,而不仅仅是保存它。
验证实体服务器端的最佳方法是什么?我正在考虑在我的服务类中创建一个 IsValid 方法并返回一个错误列表,然后将其添加到控制器中的 ModelState 中。或者,也许使用自定义验证属性并在客户端执行,并在单击保存时以某种方式禁用验证,并为提交按钮启用它。似乎应该有一个更优雅的解决方案。有没有人有什么建议?
编辑:这是我用于我的属性的代码:
public class RequiredIfAttribute : ValidationAttribute
{
RequiredAttribute _innerAttribute = new RequiredAttribute();
private string _dependentProperty { get; set; }
private object _targetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this._dependentProperty = dependentProperty;
this._targetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var field = validationContext.ObjectType.GetProperty(_dependentProperty);
if (field != null)
{
var …
Run Code Online (Sandbox Code Playgroud)