简体   繁体   中英

Textbox input control (number of characters, type of characters)

I have an asp:textbox to take a container number from the user and validate it, how can I make sure that the entered string is exactly 11 characters long of which

  1. The first 4 characters are ordinary English characters
  2. The 4th character must be one of the following {U or J or Z}
  3. The remaining (9 characters) are digits.

Example > "CRLU123456789"

I would recommend that you use a RegularExpressionValidator . They are very easy to markup:

<asp:RegularExpressionValidator
    ControlToValidate="NameOfTextBox"  <!-- the input text box name -->
    ValidationExpression="[a-zA-Z]{4}[UJZ]\d{9}"
    ErrorMessage="Please enter a valid container number."
    Display="Dynamic"  <!-- this means it's display: none when no error -->
    EnabledClientScript="true"  <!-- this will perform JavaScript validation -->
    runat="server" />

Now, with the EnabledClientScript="true" it will actually validate the control with JavaScript, if it's enabled, but because you still can't rely on that you need to validate server-side too. So, what you'll do is in the button click, where you want validation to occur, the first block of code should be:

this.Validate();    // validates all Validators on the page
if (!this.IsValid) { return; }

and when you post back the error message will be displayed.

对此ValidationExpression使用RegularExpressionValidator控件: [a-zA-Z]{4}[ujzUJZ][0-9]{9}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM