Home > Back-end >  Data Annotation model validation for Required attribute
Data Annotation model validation for Required attribute

Time:05-20

In my web api project, I have this code which uses Data Annotation Required attribute to validate. But when I test it using Postman, it can still go through.

    public async Task<ActionResult> IsAccountClosed([Required] string nric)
    {
      // code removed for brevity
    }

enter image description here

CodePudding user response:

"In my web api project, I have this code which uses Data Annotation Required attribute to validate. But when I test it using Postman, it can still go through.?"

The [Required] attribute allows you to use ModelState.IsValid construct. As model binding and model validation occur before the execution of a controller action or a Razor Pages handler method.it's the app's responsibility to inspect ModelState.IsValid and react appropriately. So you should use ModelState.IsValid inside then it would act what you are expecting.

Controller

public async Task<ActionResult> IsAccountClosed([Required] string nric)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            return Ok();
           
        }

Note: Its should also work even you don't use ModelState.IsValid attribute because model validation executes before the enter image description here

Hope above steps guided you accordingly.

  • Related