开发者

Text box validation in c#

开发者 https://www.devze.com 2023-02-12 03:16 出处:网络
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 val开发者_如何学编程idation che

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 val开发者_如何学编程idation check, but I can't seem to find it.

Any suggestions?


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号