Reputation: 31
I get a JSON string in a body of a POST Request like this:
{
"payload": {
"email": "[email protected]",
"password": "example"
}
}
My question is, how can I validate the email and password field in ASP.NET Core 2.0?
Upvotes: 1
Views: 1306
Reputation: 2092
First, create the model with data annotation validation attributes. There are a number of out of the box validation attributes, and you can also create your own.
public class SomeRequest
{
[Required]
public SomeRequestPayload Payload {get;set;}
}
public class SomeRequestPayload
{
[RegularExpression("some regex", ErrorMessage = "Invalid Email")]
[Required]
public string Email {get;set;}
[RegularExpression("some regex", ErrorMessage = "Invalid Password")]
[Required]
public string Password {get;set;}
}
Then check the ModelState
in your controller action. MVC will validate the model and hold any errors in the ModelState
when it binds the request body to the method parameter.
[HttpPost("")]
public async Task<IActionResult> PostPayload([FromBody] SomeRequest someRequest)
{
//checking if there was even a body sent
if(someRequest == null)
return this.BadRequest("empty");
//checking if the body had any errors
if(!this.ModelState.IsValid)
return this.BadRequest(this.ModelState);
//do insert here
return this.Created("someLocation", someModel);
}
Upvotes: 1
Reputation: 738
There are many way to validate those fields. I prefer to use FluentValidation
library with additional package FluentValidation.AspNetCore
, which integrates validation into ASP.NET Core pipeline
.
There is a great blog-post about using this approach.
Put simply, you should do a few steps:
dotnet add package FluentValidation.AspNetCore
public class AuthViewModelValidator : AbstractValidator<AuthViewModel>
{
public AuthViewModelValidator()
{
RuleFor(reg => reg.Email).NotEmpty().EmailAddress();
RuleFor(reg => reg.Password).NotEmpty();
}
}
Add some code to ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddFluentValidation(fvc =>
fvc.RegisterValidatorsFromAssemblyContaining<Startup>());
}
And finally validate a model
[HttpPost]
public IActionResult FormValidation(AuthViewModel model)
{
if (this.ModelState.IsValid) {
ViewBag.SuccessMessage = "Great!";
}
return View();
}
Upvotes: 0