BennySkate
BennySkate

Reputation: 1

C# WPF using Regex validation. How to check numbers between a range?

I'm writing a program for Uni which requires some basic validation.

I have a textbox which allows the user to input their age. I have successfully written a Regex expression which checks if the value entered into the textbox contains numeric values only and is two characters long:

Regex agePattern = new Regex(@"^[0-9]{1,2}\z$"); // Age entered must be numeric characters only (0-9) and may only be two charaters long

        if (agePattern.IsMatch(ageBox.Text) == false)
        {
            MessageBox.Show("Customer's age is not valid. Age must be in numeric format & can only be two characters long"); // If Regex pattern & entered string DO NOT match - user get's this message
            return;
        }
        else
        {
            // do something
        }

My question is, can I extend my Regex expression to constrain age values between 1 and 99?

I've not written any Regex before and I'm struggling.

Thanks!

Upvotes: 0

Views: 2221

Answers (3)

Armali
Armali

Reputation: 19375

Try this regex:

^[1-9]?[0-9]?\z

This matches an empty input (since both digits are optional) as well as 0. Fewer ? are better:

^[1-9][0-9]?$

Try it with A Better .NET Regular Expression Tester (most other online testers don't allow to specify an empty source).

Upvotes: 0

Try this regex:

^[1-9]?[0-9]?\z

Or skip regex, parse the text as int and write a function which decide input is between 1 and 99.

Upvotes: 0

Bas
Bas

Reputation: 27085

How about parsing an integer instead?

bool IsValidAge(string ageString) {
   int age;
   return int.TryParse(ageString, out age) && age >= 1 && age <= 99;
}

Upvotes: 1

Related Questions