在研究了在MVC中实现自定义表单验证规则的各种方法之后,我发现,我最初认为这是一个简单的验证,比我预期的要复杂得多。
我有2个文本输入,需要填充一个或另一个(或两者)。如果两者都是NullOrEmpty
,我们需要抛出错误。
我在尝试对多个字段进行验证时发现DataAnnotations
有限制,让我突出显示两个输入并抛出一个错误。这是一些初学者的天真吗?
我还和FluentValidation
一起玩,但无法得到我追求的结果。
目前我使用以下方法在控制器中抛出错误:
ModelState.AddModelError("PropertyName", "You need to enter a Property Number or a Property Name")
ModelState.AddModelError("PropertyNumber", String.Empty)
这使我突出显示了字段和服务器端验证。我现在发现很难在不使用DataAnnotations的情况下绑定自定义客户端验证。
有没有人对如何正确地做这件事有任何建议?任何帮助或建议将不胜感激。我需要在两个字段的服务器/客户端上进行验证,并突出显示和单个错误消息。
提前致谢。
答案 0 :(得分:0)
[Fool proof] [1] 验证库涵盖了几乎所有类型的验证方案。
[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
Applied to a Model:
public class CreateUserViewModel
{
[Required]
public string Username { get; set; }
[Required]
public string Department { get; set; }
[RequiredIfEmpty(ErrorMessage="error message"]
public string Role { get; set; }
}