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. 4000,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: