用于匹配正则表达式的JavaScript函数

时间:2018-02-04 01:42:45

标签: javascript asp.net regex

我在ASP.net webform上有一个文本框,预期值的格式为AA000000。 我使用自定义验证器调用Javascript函数以使用正则表达式验证文本。但这还没有奏效。 请指教。

<asp:TextBox ID="txtPassportNumber" runat="server" Visible="True" Width="576px" AutoPostBack="True" ControlToValidate="txtIdentityNumber"></asp:TextBox>
<asp:RequiredFieldValidator ID="valRequiredPassportNumber" runat="server" ErrorMessage="Passport number is required." ControlToValidate="txtPassportNumber" ValidateRequestMode="Enabled" Font-Italic="True" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="valCustomPassportNumber" runat="server" ErrorMessage="Please provide a valid Passport number." ControlToValidate="txtPassportNumber" ClientValidationFunction="validatePassportNumber" Font-Italic="True" ForeColor="Red" SetFocusOnError="True"></asp:CustomValidator>

JS

< script >
  function validatePassportNumber(oSrc, args) {
    if (document.getElementById("txtPassportNumber").value != "") {
      var inputString = document.getElementById("txtPassportNumber").value;
      //var pattern = new RegExp("/[a-zA-Z]{2}[0-9]{6}/");
      var pattern = /[a-zA-Z]{2}[0-9]{6}/;
      if (pattern.test(inputString) == true)
        args.IsValid = true
      else
        args.IsValid = false
    }
  } <script >

2 个答案:

答案 0 :(得分:0)

使用此:^[a-zA-Z]{2}\d{6}$
在javascript:/^[a-zA-Z]{2}\d{6}$/gm

^           : First of line  
[a-zA-Z]{2} : any character with length 2  
\d{6}       : any digit(number) with length 6  
$           : End of line

Demo

答案 1 :(得分:0)

您可以使用此正则表达式:

^[A-Z]{2}[0-9]{6}$

var pattern = /^[A-Z]{2}[0-9]{6}$/;

那就匹配

^        # The beginning of the string
[A-Z]{2} # 2 Uppercase characters
[0-9]{6} # 6 digits
$        # The end of the string