0

I need to do MVC unobtrusive client side validation using regular expression in my ASP.NET MVC 5 project.

Valid Input is comma separated string values, for example: string1, string2, string 3 etc.

I tried below regEx pattern for comma separated strings but it's not working as expected. Could anyone tell me what's wrong in below expression ?

[RegularExpression(@"/^[a-zA-Z]{1,20},[a-zA-Z]{1,20}$/",
                        ErrorMessage = "Please enter comma separated list")]
    public string SettingOptions { get; set; }

Thanks in Advance.

1
  • Do you want to enforce the number used should only be in range 1 to 20? Commented Jun 29, 2015 at 6:14

3 Answers 3

2

This should work for your example string1, string2, string 3 etc:

^[a-zA-Z0-9 ,]+$


[RegularExpression(@"^[a-zA-Z0-9 ,]+$"]
Sign up to request clarification or add additional context in comments.

Comments

0

Just try this.

"[a-zA-Z]{1,20},[a-zA-Z]{1,20}"

Because ^ and $ denotes the starting and ending of string. It will allow only string1,string2.

2 Comments

This only matches on two comma seperated strings. Not 3 as the example states.
yes but as I stated.. Only two not more not less, also spaces will not be possible between the seperated values.
0

To match your regex against a comma separated string would use a regex such as:

[0-9a-zA-Z]+(,[0-9a-zA-Z]+)*

If you wish to remove the numbers then you can drop the 0-9 requirement.

After more review there could be small discrepancies with this regex and came up with an alternative that may be more helpful. The previous regex would not allow for spaces in each separated string item.

^([a-zA-Z0-9]+,?\s*)+$

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.