Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. :)

like image 225
Rajivrocks Avatar asked Oct 20 '25 08:10

Rajivrocks


1 Answers

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);
}
like image 84
Derviş Kayımbaşıoğlu Avatar answered Oct 21 '25 22:10

Derviş Kayımbaşıoğlu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!