9

I want to put a validation that the user always enters a value in the textbox before submiting the form. But the check that I have put allows user to enter white spaces and continue submitting the form. So, how to put the check so that the user in not able to submit the form if there are only white spaces in the textbox.

1
  • 2
    You've tagged the question winforms, but it sounds as though you're asking about webforms. Which is it?
    – Tom W
    Nov 17, 2010 at 9:46

3 Answers 3

7

You can make your own custom validation function. This may be very naive, but somehow it will work.

private bool WithErrors()
{
    if(textBox1.Text.Trim() == String.Empty) 
        return true; // Returns true if no input or only space is found
    if(textBox2.Text.Trim() == String.Empty)
        return true;
    // Other textBoxes.

    return false;
}

private void buttonSubmit_Click(object sender, EventArgs e)
{
    if(WithErrors())
    {
        // Notify user for error.
    }
    else
    {
        // Do whatever here... Submit
    }
}
6

in NET4.0 there is a nice function

 if(string.IsNullOrWhiteSpace(textBox1.Text))
{
   //raise your validation exception
}
else {
  //go to submit
}
4

It can be easily be done using error provider here is the code.Error Provider you can find in your toolbox.

    private void btnsubmit_Click(object sender, EventArgs e)
            {

                if (string.IsNullOrEmpty(txtname.Text))
                {

                    txtname.Focus();
                    errorProvider1.SetError(txtname, "Please Enter User Name");
                }

                if (string.IsNullOrEmpty(txtroll.Text)) {
                    txtroll.Focus();
                    errorProvider1.SetError(txtroll, "Please Enter Student Roll NO");
                }
}

Here is output image

enter image description here

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.