简体   繁体   中英

Field validation in ASP.NET Core 2.0

I get a JSON string in a body of a POST Request like this:

{
  "payload": {
    "email": "example@test.com",
    "password": "example"
  }
}

My question is, how can I validate the email and password field in ASP.NET Core 2.0 ?

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);
}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM