Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression data annotation disallowed start / end spaces (similar to trim)

I am using a regular expression data annotation to validate a street address field to contains numbers, letters, and spaces (in between). I want the data annotation to throw an error if the street field contains spaces at the beginning or the end of the text entered by the user.

Example:

// [123 Fake Street] = valid
// [   123 Fake Street] = not valid
// [   123 Fake Street    ] = not valid
// [123 Fake Street   ] = not valid

This is what I have so far:

[RegularExpression(@"^[a-zA-Z 0-9]+$", ErrorMessage = "Street Address not valid.")]

Any help would be appreciated.

Thanks

like image 356
Farhan Ahmad Avatar asked Oct 16 '25 07:10

Farhan Ahmad


1 Answers

You just need to change a little:

"^(?:[a-zA-Z0-9]+\s?)+[a-zA-Z0-9]+$" 

This means:

  1. Get 1 or more letters or numbers and an optional space and repeat 1 or more times;
  2. Finish with one or more letters or numbers

You can also write:

"^(?:\w+\s?)+\w+$" 
like image 192
Ricardo Souza Avatar answered Oct 17 '25 22:10

Ricardo Souza



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!