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

asp.net-mvc, c#, data-annotations, regex

Solution

You just need to change a little:

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

This means:

- Get 1 or more letters or numbers and an optional space and repeat 1 or more times;

- Finish with one or more letters or numbers

You can also write:

"^(?:\w+\s?)+\w+$" 

Problem

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

Original source