Mike
Mike

Reputation: 2313

Text box validation not working

Right now the code below tests for a blank text box. If it is blank it returns the error stated below the if statement. That works fine, but I also want it to check for white spaces. I have tried the following for the first one:

if (String.IsNullOrWhiteSpace(txtFirstName.Text))

It does not work though. I typed the word "Bike" into the text box, but I spelled it like "B ike" with a space to see if it would return the error message and it didn't.

public partial class frmPersonnel : System.Web.UI.Page
{
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //lblError.Text = "";
        try
        {
            if (txtFirstName.Text == "")
            {
                txtFirstName.BackColor = System.Drawing.Color.Yellow;
                lblError.Text += "Please enter first name<br />";
            } 

            if (txtLastName.Text == "")
            {
                txtLastName.BackColor = System.Drawing.Color.Yellow;
                lblError.Text += "Please enter last name! <br />";
            }
            if (txtPayRate.Text == "")
            {
                txtPayRate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text += "Please enter pay rate! <br />";
            }
            if (txtStartDate.Text == "")
            {
                txtStartDate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text += "Please enter start date! <br />";
            }
            if (txtEndDate.Text == "")
            {
                txtEndDate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text += "Please enter end date! <br />";
            }

            DateTime dt1;
            DateTime dt2;

            dt1 = DateTime.Parse(txtStartDate.Text);
            dt2 = DateTime.Parse(txtEndDate.Text);


            if (DateTime.Compare(dt1, dt2) > 0)
            {
                txtStartDate.BackColor = System.Drawing.Color.Yellow;
                txtEndDate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text += "Start Date must not be greater than End Date! <br />";
            }

            else
            {
                Session["txtFirstName"] = txtFirstName.Text;
                Session["txtLastName"] = txtLastName.Text;
                Session["txtPayRate"] = txtPayRate.Text;
                Session["txtStartDate"] = txtStartDate.Text;
                Session["txtEndDate"] = txtEndDate.Text;
                Server.Transfer("frmPersonalVerified.aspx");
            }
        }
        catch (Exception)
        {

        }
    }
}

Upvotes: 0

Views: 1518

Answers (7)

John
John

Reputation: 644

if (string.IsNullOrEmpty((TextBox1.Text ?? string.Empty).Trim()))

Upvotes: 0

Oded
Oded

Reputation: 499002

I would change the following type of test:

if (txtFirstName.Text == "")

To:

if (string.IsNullOrWhiteSpace(txtFirstName.Text)) // .NET 4.0+

if (string.IsNullOrEmpty(txtFirstName.Text)) // .NET before 4.0

And for your additional test (no spaces allowed in the string):

if (string.IsNullOrWhiteSpace(txtFirstName.Text) && !txtFirstName.Text.Contains(" ")) // .NET 4.0+

if (string.IsNullOrEmpty(txtFirstName.Text) && !txtFirstName.Text.Contains(" ")) // .NET before 4.0

Note:

You will need to check that lblError.Text doesn't contain anything in order to continue to the next page, as this is what holds your errors. I can only see the DateTime test, so even if any of your txt controls have failed the validation, you still transfer.

Upvotes: 3

Joel Etherton
Joel Etherton

Reputation: 37533

To do this kind of validation in Asp.Net you should really be using the built-in validators. If this is not desirable to you, then you might consider making your comparisons regular expression based to apply a tighter control over the inputs. In the case of your B ike example, you would want something like:

if (!Regex.IsMatch(txtFirstName.Text, @"^(\w)+$"))
{
    txtFirstName.BackColor = System.Drawing.Color.Yellow;
    lblError.Text += "Please enter first name<br />";
} 

The regular expression above will make sure that there is at least one viable word character and will parse the entire string returning false if any white space is detected. It would be useful to do this for similar controls and modify the expression pattern to meet the needs of any different criteria.

Edit:
I left this off as assumed, but it might as well be mentioned. In order to use the Regex, you'll need to add the following using statement at the top of your code:

using System.Text.RegularExpressions;

Edit 2:
I discounted these items because you didn't ask about them, but I'll address them here since they're providing you trouble. To change the color of the TextBox in the web page you'll need to apply css to it.

Define a class in your style sheet that looks like:

.yellowBox
{
    background-color: #cccc00;   
}

Then in your block, apply the style like so:

if (!Regex.IsMatch(txtFirstName.Text, @"^(\w)+$"))
{
    // Define a class in your style sheet that looks like
    txtFirstName.CssClass = "yellowBox";

    // Obviously you have a lblError control, but is
    // that control visible? If not you must change its
    // visibility. This should be done after all of the
    // processing blocks are complete.
    lblError.Text += "Please enter first name<br />";
}
if ( ... next condition ... )
{

    ... 1, 2, skip a few ...
}

// If you've appended something to the lblError
// then make it visible.
if (lblError.Text.Trim().Length > 0) 
    lblError.Visible = true;

Upvotes: 1

Harry
Harry

Reputation: 1353

There are various Validation possibilities, maybe have a look at this.

Else you can use something like

if (txtFirstName.Text == "" && txtFirstName.Text.indexOf(" ") == -1)

which checks for whitespaces :)

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151594

You should check the manual:

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

Indicates whether a specified string is null, empty, or consists only of white-space characters.

So use another function if you don't want any spaces (or other whitespace) to be present, like Contains or using a RegEx.

Upvotes: 0

William
William

Reputation: 8067

String.IsNullOrWhiteSpace returns true for a null string or a string that is purely whitespace For example " ".

If you do not want to allow spaces in the string ie ("B ike") test the string value for spaces using Contains(' ').

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12458

What about:

if (txtFirstName.Text.Contains(" "))
{
    txtFirstName.BackColor = System.Drawing.Color.Yellow;
    lblError.Text += "Please enter first name without blanks<br />";             
}  

Upvotes: 0

Related Questions