Reputation: 348
I need to restrict a string to only allow letters, numbers, hyphens, ampersands, apostrophes and single spaces.
From a bit of searching I've got this so far:
^[A-Za-z0-9-'&\s]{1,}$
But this allows for double spaces. How do I write the regular expression so that it only allows single spaces (there might not be any at all)?
Upvotes: 4
Views: 1127
Reputation: 993
I have tried with different scenario it works fine with me ^\b(?!.*?\s{2})[A-Za-z0-9 ]{1,50}\b$
[RegularExpression(@"^\b(?!.*?\s{2})[A-Za-z0-9 ]{1,50}\b$", ErrorMessage ="String is not valid"]
public string FirstName{ get; set; }
Upvotes: 0
Reputation: 239814
Match any of the other allowed values, followed by an optional single space:
^\s?([A-Za-z0-9-'&]\s?){1,}$
(I also added an optional one at the start, if that's allowed)
Upvotes: 7