Supposing that i have implemented model validations in the model object that will be transferred from the client to the server. What is the purpose of retesting if the model is valid if (ModelState.IsValid)
in the endpoint ?
When i make a call to the endpoint (without the if statement) it gaves me the the list of the errors in case i miss some rules like : Email Format, Required Field ...
In this case supposing that i entered a null Email :
Model :
public class LogInModel
{
[Required]
[EmailAddress]
public string Email { get; set;
}
Endpoint Controller
public async Task<IActionResult> LogIn([FromBody] LogInModel logInModel)
{
var result = await _accountRepository.LogInAsync(logInModel);
/*rest of the code ...*/
}
HttpResonse
{
"errors": {
"FirstName": [
"The FirstName field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-7f0c96d3c37b2f4d9be35f967083688f-96012fc23469ad4d-00"
}
I want to know what is the purpose of ModelState.IsValid in this case ?
CodePudding user response:
Using this feature is depend on your requirements.
The validation normally will happened at client-side and server-side. The client side contains the client validation which will check the application's states by using jquery.validate.unobtrusive
library.
If you are using it like this, there is no need to use ModelState.IsValid to check the states at MVC controller.
If your client doesn't use the client library at clinet side, you need to check the ModelState.IsValid status.