5

I need to validate that the user entered text in the format:

####-#####-####-###

Can I do this using Regex.Match?

1 Answer 1

7

I would do something like this:

private static readonly Regex _validator = 
    new Regex(@"^\d{4}-\d{5}-\d{4}-\d{3}$", RegexOptions.Compiled);
private static bool ValidateInput(string input)
{
    input = (input ?? string.Empty);
    if (input.Length != 19)
    {
        return false;
    }
    return _validator.IsMatch(input);
}
Sign up to request clarification or add additional context in comments.

9 Comments

Isn't that only for numbers? It is true that the question does not specify exactly what "text" is.
@Liviu - I usually interpret # as a numeric placeholder.
why go through the trouble of checking the length and and having multiple returns, is the precompiled regex operation so expensive that it's not worth doing? I would just let it fail the regex and make the method simpler. I do however like that you are using \d instead of [0-9]
@dstarh - I don't consider checking the length to be much trouble. It is such an easy way to validate the input. In a high throughput process it can make a difference in performance as well. (Not much I admit.)
Should those literal - characters, code point 45 HYPHEN-MINUS, be better written as \p{Pd} for any sort of dash punctuation? And if you wanted them to be all of the same sort, you could write ^\d{4}(\p{Pd})\d{5}\1\d{4}\p{Pd}\1\d{3}$.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.