Text box validation not working

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

    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;
    
    0 讨论(0)
提交回复
热议问题