Text box validation not working

前端 未结 7 1437
[愿得一人]
[愿得一人] 2020-12-12 07:40

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

7条回答
  •  情深已故
    2020-12-12 08:00

    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.

提交回复
热议问题