chamara
chamara

Reputation: 12709

Regular Expression allow only numbers, commas and dashes

I'm trying to come up with a Data Annotation regular expression to match the following formats.

34

38-30

100,25-30

4-5,5,1-5

Basically the expression should only allow numbers, -(dash) and ,(comma) in any order

I tried following but couldn't get it working.

[RegularExpression(@"(0-9 .&'-,]+)", ErrorMessage ="Lot numbers are invalid.")]

Upvotes: 3

Views: 17352

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

I think your use case is having a CSV list of numbers, or ranges of numbers (identified as a number followed by a dash followed by another number). We can use the following regex:

[0-9]+(?:-[0-9]+)?(,[0-9]+(?:-[0-9]+)?)*

This regex matches a number, followed by an optional dash and another number, that quantity then followed by comma and another similar term, any number of times.

In the demo below I added anchors on both sides of the regex. Whether you need to do this depends on how you plan to use the pattern.

Demo

Upvotes: 5

Anis Alibegić
Anis Alibegić

Reputation: 3230

It's ^[0-9,-]*$. Check out this demo.

Upvotes: 8

Related Questions