1

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?

5
  • There are many ways to do validation. A what have you tried? Commented Jul 24, 2018 at 19:40
  • I tried the build in functionallity of ASP with the annotations and the modelstate. But I don't know if I should create one request class for every request or one class for one request. Commented Jul 24, 2018 at 19:57
  • the number of request models depends on your entity structure. you can inherit attributes from base classes if you want to have some re usability. Commented Jul 24, 2018 at 21:16
  • You need to give us a little more detail. What kind of validation do you want? Do you want server side validation or client side validation (or both)? What have you tried so far? What has worked, what hasn't? Commented Jul 24, 2018 at 21:26
  • That was my fault, I want server-side validation. I use C# in the backend. My problem is that I am not sure if it is good to create more than one request class. Commented Jul 26, 2018 at 17:53

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.