5

I have a form with a text box that should only accept 4 digit year values between 1980-2011. I'm sure there should be a simple c# validation control to implement this validation check, but I can't seem to find it.

Any suggestions?

3
  • Windows Forms doesn't have validation controls Commented Feb 21, 2011 at 12:28
  • What is wrong with checkin it on keypress? UC that you'd find would do the same thing anyway.. Commented Feb 21, 2011 at 12:29
  • So what would be the best way to implement checks? Commented Feb 21, 2011 at 12:30

4 Answers 4

4

Catch Validating event and add you validation code in there.

For a complete example check MSDN page.

For simple validation you can also use a MaskedTextBox.

Sign up to request clarification or add additional context in comments.

Comments

2

First I'd say, use the max length property set to 4 so that no extra characters can be entered

Beyond that you would have to hook up your own controls to validate it (could be a on text changed validation, on lost focus, etc) that would check that only digits are entered and they are between your specified values

Comments

1

A MaskedTextBox would do the trick. Set the mask to your needs: msdn. But I doubt it will check if the value is between a range. It probably only checks if the value is a integer.

Comments

0

Ok, I'm not going to write all the code here but here's what I'd do:

In textchanged event of your textbox;

  • Check if entered value is numeric
  • Check if it meets the pattern (compare chars with what you want)

For this one, you need to compare each number one by one. I'd suggest you to write a method which parses the text and compares them with your expected values. Something like this:

private bool IsNumberValid(string text) { String min = "1980",max=2011; try { int minNumber = Convert.ToInt32(min.Substring(0,text.length)); int maxNumber = Convert.ToInt32(max.Substring(0,text.length)); int myNumber = Convert.ToInt32(text); if(myNumber <= max && myNumber >= min) return true; } catch(Exception ex) { return false; // number is not numeric } return false; } 

There may be small errors, didn't write it in VS. You'd need to check the length of the text and not call this method if it is 0.

1 Comment

I don't get this code, why is the Min and Max specified as a string at all and not a int, why are they declared in the method meaning they'll be recreated and re parsed every time you check it's valid, this seems like a strange approach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.