This is pretty easy to do with a regular expression.
To learn about that you can use this site as a starting point:
Regular Expression Info[
^]
And why not use the
Validating event[
^] for the text box? It is kind of made for this purpose. And it will trigger when the focus leaves the control.
Make sure to add
using System.Text.RegularExpressions;
also add this as a member of your class
private static Regex exprNumber = new Regex("^(405|505)(19[5-9][0-9]|[2-9][0-9]{3})[0-9]{6}$");
* The ^ anchor will make sure that you start the evaluation at the start of the string
* (405|505) means either 405 or 505
* 19[5-9][0-9] means 19 followed by a digit >=5 followed by 1 digit in the range of 0-9.
* 2[0-9]{3} means 2 - 9 followed by 3 digits in the range of 0-9. 2000 - 9999
* (19[5-9][0-9]|2[0-9]{3}) means either a number between 1950-1999 or between 2000-9999
* [0-9]{6} means exactly 6 digits in the range 0-9
* The $ anchor means that no extra characters can be matched.
* The total number of allowed characters is 13
Note: [0-9] can be replaced by \d, which is shorter but can be more difficult to read
In the event you can do something like this
private void txtsfn_Validating(object sender, CancelEventArgs e)
{
if (!exprNumber.IsMatch(txtsfn.Text))
{
e.Cancel = true;
txtsfn.Focus();
}
}
[UPDATE]
I don't know a way to check for current year in pure regular expression, but you can do it with some extra coding.
(Maybe there is a way to do it in regex only, but in that case you better ask separate question)
First change the expression a bit
private static Regex exprNumber = new Regex("^(405|505)(?<year>19[5-9][0-9]|[2-9][0-9]{3})[0-9]{6}$");
(?<year>19...) represents a named group that makes it easy to extract the year part later
Then change your validation code a little:
private void txtsfn_Validating(object sender, CancelEventArgs e)
{
Match m = exprNumber.Match(txtsfn.Text);
int testedYear = 0;
int.TryParse(m.Groups["year"].Value, out testedYear);
int currentYear = DateTime.Now.Year;
if (!m.Success || testedYear > currentYear)
{
e.Cancel = true;
txtsfn.Focus();
}
}