Rajivrocks
Rajivrocks

Reputation: 151

Use regex to validate in a controller

to start of Sorry if i'm a complete and utter noob but i got the task of possibly using regex to verify inputs of users on a register page. I'm 100% back-end so i see no front end. so what my classmate told me is that i should use regex in the controller but i'm only writing API's. Is it possible to use REGEX in an API? also i tried specifying stuff in my model like

public string email { get; set; }
    [Display(Name = "Email address")]
    [Required(ErrorMessage = "The email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]

But when i update my db and check the SQL in my db it doesn't say any of this stuff and when i send a post request with userdata it just allows me to put in anything as an email address. sorry if i didn't describe some stuff clearly i hope anyone could help me in anyway. we could just drop regex and make it full front-end checking i think but it would be nice to know how to do this for in the future. :)

Upvotes: 4

Views: 2245

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30625

Annotations must come before property

[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string email { get; set; }

In this way your validation must work

you can also use regex

    [RegularExpression(@"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9.-]+\.[A-Z]{2,}$", 
        ErrorMessage = "Characters are not allowed.")]

Edit: Also In your Action Method

[HttpPost]
public IActionResult Post(string email)
{
    if (ModelState.IsValid)
    {
        //return success result
    }

    return BadRequest(ModelState);
}

Upvotes: 6

Related Questions