Question

I have a form where I need to validate the textboxes like Firstname, Middlename, Lastname, emailId, date, mobilenumber. The validation should happen when a user starts typing in the textbox. errorprovider should show message under textbox if a user enters numbers in place of text and text in place of numbers. I got to know about implicit validation and explicit validation but I feel better to use implicit validation only because its on time error provider when user looses focus on text box or if he shifts to another textbox. I've posed this kind of question with a explicit validation code but no one responded me. So Im making it simple to get help. Do not think I havent done enough research before posting this question.

Was it helpful?

Solution

If you have a very specific validation to do, Marc's answer is correct. However, if you only ensure the "enter number instead of letters" or "enter letters instead of numbers" thing, a MaskedTextBox would do the job better than you (user wouldn't be able to answer incorrect data, and you can still warn them by handling the MaskInputRejected event)

http://msdn.microsoft.com/en-us/library/kkx4h3az(v=vs.100).aspx

OTHER TIPS

You should take a look to the TextChanged Event in of your textbox.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged.aspx

This event is raised if the Text property is changed by either a programmatic modification or user interaction.

I would do something like this

private void TextBoxExample_TextChanged(object sender, EventArgs e)
{
   TextBox box = sender as TextBox;

   if (box.Text.Contains("Example"))
   {
      LabelError.Text = "Error";
   }
   else
   {
      LabelError.Text = string.Empty;
   }
}

Hope it helps :)

You can also use keyPressEvent to Avoid the entering the numerical values in the textboxes it will not allow the numerical chars in the text box

private void textboxName_KeyPress(object sender, KeyPressEventArgs e)
    {
        //not allowing the non character values
        if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar) && !(e.KeyChar == (char)Keys.Back) && !(e.KeyChar == (char)Keys.Left) && !(e.KeyChar == (char)Keys.Right) && !(e.KeyChar == (char)Keys.Space) && !char.IsPunctuation(e.KeyChar))
        {
            e.Handled = true;
        }
    } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top