Wednesday 4 November 2015

validate a textbox to enter mobile numbers in xxx-xxx-xxxx format using c#

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
           string sVal = textBox1.Text;
         
                if (textBox1.TextLength <= 8)
                {
                    if (!string.IsNullOrEmpty(sVal) && e.KeyCode != Keys.Back)
                    {
                        sVal = sVal.Replace("-", "");
                        string newst = Regex.Replace(sVal, ".{3}", "$0-");
                        textBox1.Text = newst;
                        textBox1.SelectionStart = textBox1.Text.Length;
                    }
                }
                 if(textBox1.TextLength >= 12)
                {
                    e.SuppressKeyPress = true;
                }
         
        }

No comments:

Post a Comment