[英]How to validate model depends on bool datatype value using asp.net core web api
I have created a model using asp.net core web API and I have to validate the property depends on bool data type property value. 我已经使用asp.net核心Web API创建了一个模型,并且必须验证该属性取决于bool数据类型属性值。
If the IsWaitingList
property is true , the WaitingListEncounterOrOtherEncounter
property is required property, else it's not a mandatory field. 如果
IsWaitingList
属性为true,则WaitingListEncounterOrOtherEncounter
属性为必填属性,否则不是必填字段。
public class CenterConfiguration
{
public Guid Id { get; set; } = Guid.NewGuid();
public bool? IsWaitingList { get; set; }
[Required(ErrorMessage = "Please enter waiting list encounter or other encounter")]
public int WaitingListEncounterOrOtherEncounter { get; set; }
}
If anybody knows, please let me know. 如果有人知道,请告诉我。
You can implement IValidatableObject
to check complex validation conditions. 您可以实现
IValidatableObject
来检查复杂的验证条件。
public class CenterConfiguration : IValidatableObject {
public Guid Id { get; set; } = Guid.NewGuid();
public bool? IsWaitingList { get; set; }
public int? WaitingListEncounterOrOtherEncounter { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (IsWaitingList && !WaitingListEncounterOrOtherEncounter.HasValue) {
yield return new ValidationResult(
"Please enter waiting list encounter or other encounter",
new[] { "WaitingListEncounterOrOtherEncounter" }
);
}
}
}
Also note that I changed WaitingListEncounterOrOtherEncounter
from int
to int?
另请注意,我将
WaitingListEncounterOrOtherEncounter
从int
更改为int?
so you can actually leave this value blank. 因此您实际上可以将此值留空。
See also How do I use IValidatableObject? 另请参阅如何使用IValidatableObject?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.