[英]How to stop validation after first error in ASP.NET Core 2.1
I know this question is asked several times for other frameworks and languages but I wanted to know how can I really stop my model validation once it gets the first error in ASP.NET Core 2.1? 我知道针对其他框架和语言也曾多次问过这个问题,但我想知道一旦在ASP.NET Core 2.1中遇到第一个错误,如何才能真正停止模型验证?
[Required(ErrorMessage = Email.requiredErrorMessage)]
[DataType(DataType.EmailAddress, ErrorMessage = Email.formatErrorMessage)]
[StringLength(Email.maximumLength, MinimumLength = Email.minimumLength, ErrorMessage = Email.rangeErrorMessage)]
[EmailExists(ErrorMessage = Email.doesNotExistsMessage)]
public string email { get; set; }
[Required(ErrorMessage = ConfirmationCode.requiredErrorMessage)]
[RegularExpression(ConfirmationCode.regularExpression, ErrorMessage = ConfirmationCode.formatErrorMessage)]
public string confirmationCode { get; set; }
Above code is API model validation and upon making a Patch request, I receive following response: 上面的代码是API模型验证,在提出补丁请求后,我收到以下响应:
"email":[
"This email does not exist in database"
],
"confirmationCode":[
"Confirmation code format is invalid"
]
}
I do not want model validation to continue when it has ensured that email doesn't exist in database, just return that error and do not continue the validation anymore. 当它确保数据库中不存在电子邮件时,我不希望模型验证继续进行,仅返回该错误并且不再继续验证。
You can configure the maximum number of errors MVC will process when you register the MVC services: 您可以配置注册MVC服务时MVC将处理的最大错误数:
services.AddMvc(options => options.MaxModelValidationErrors = 1);
See https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#model-state 参见https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#model-state
MVC will continue validating fields until reaches the maximum number of errors (200 by default).
MVC将继续验证字段,直到达到最大错误数(默认为200)。 You can configure this number by inserting the following code into the ConfigureServices method in the Startup.cs file:
您可以通过将以下代码插入Startup.cs文件的ConfigureServices方法中来配置此数字:
That being said, you won't necessarily have control over which order those errors are processed in. To handle that, you might need to add some custom validation logic which is also discussed in the above link. 话虽如此,您不一定会控制处理这些错误的顺序。要处理该错误,您可能需要添加一些自定义验证逻辑,以上链接中也对此进行了讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.