4

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)?

0

3 Answers 3

7

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)

Sign up to request clarification or add additional context in comments.

Comments

1
Try this
^([A-Za-z0-9-'&]+\s?)+$

Comments

0

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.