Pinal Dave
Pinal Dave

Reputation: 533

ASP.NET MVC regular expression for comma separated strings

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.

Upvotes: 0

Views: 1670

Answers (3)

SBirthare
SBirthare

Reputation: 5137

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

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


[RegularExpression(@"^[a-zA-Z0-9 ,]+$"]

Upvotes: 2

Nico
Nico

Reputation: 12683

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*)+$

Upvotes: 0

Spider man
Spider man

Reputation: 3330

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.

Upvotes: 0

Related Questions