Text box validation not working

前端 未结 7 1402
[愿得一人]
[愿得一人] 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 07:49

    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 :)

    0 讨论(0)
  • 2020-12-12 07:52

    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.

    0 讨论(0)
  • 2020-12-12 07:56

    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(' ').

    0 讨论(0)
  • 2020-12-12 07:57

    What about:

    if (txtFirstName.Text.Contains(" "))
    {
        txtFirstName.BackColor = System.Drawing.Color.Yellow;
        lblError.Text += "Please enter first name without blanks<br />";             
    }  
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 08:04
    if (string.IsNullOrEmpty((TextBox1.Text ?? string.Empty).Trim()))
    
    0 讨论(0)
提交回复
热议问题