Regex: need to validate input for single, multiple or a range of postcodes
I need to validate a (four digits) postcode field that can accept:
- A single postcode (e.g. 4009) -> it has to be four digit
- Multiple postcodes separated by comma(s) (e.g. 4002,5001)
- A range of postcodes using hyphen (e.g. 4000-4010)
- Any combination of #1 and #3 separated by comma(s) (e.g. 开发者_如何学JAVA4000,4002,4005-4010,5001)
Another example of #4 will be: 4000-4007,5000
How can I do validation using regex in C#. My question is more about how to construct the pattern itself. Thank you.
Updates
This is what I came up with (using your inputs on regex):
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
var stringValue = value.ToString().Replace(" ", "");
foreach (var pc in stringValue.Split(','))
{
if(!Regex.Match(pc, @"^(\d{4})$|^(\d{4}-\d{4})$").Success)
{
return false;
}
}
return true;
}
I was kind of hoping to do the validation without having to do string.Split(). I am not sure if that's possible at all. If anyone has better idea, please post it here. Thank you.
What about ^((\d{4})([,-])?)+$
Edit: That one matched on 80789809 aswell
New: ^(\d{4})(([,-])(\d{4}))*$
Tested against:
4000,4002,4005-4010,5001 yes
4000-4007,5000 yes
4000-4010 yes
4002,5001 yes
4009 yes
40004002,4005-1010,5001 no
4000-4007, 5000 no
40004010 no
4002,50012345 no
4009, no
This should do the trick, and allow for optional whitespace between the various components:
^\s*(\d{4}(\s*-\s*\d{4}))(\s*,\s*(\d{4}(\s*-\s*\d{4})))*\s*$
The regex you need is
^\d{4}(-\d{4})?(,\d{4}(-\d{4})?)*$
This is one or more ranges separated by commas, where each range is either a single postal code or a postal code dash postal code.
If you want efficiency, you will want to make non-capturing groups, as in
^\d{4}(?:-\d{4})?(,\d{4}(?:-\d{4})?)*$
精彩评论