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 wh
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 :)
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.
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(' ').
What about:
if (txtFirstName.Text.Contains(" "))
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter first name without blanks<br />";
}
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.
if (string.IsNullOrEmpty((TextBox1.Text ?? string.Empty).Trim()))