【问题标题】:Validate Canadian Postal Code using regex使用正则表达式验证加拿大邮政编码
【发布时间】:2012-06-24 08:49:26
【问题描述】:

我编写了一个 JavaScript 来使用正则表达式验证加拿大邮政编码。

但是,它似乎不起作用:

JavaScript

如果语句:

if (myform.zip.value == "" || myform.zip.value == null || myform.zip.value == "Postal Code" || myform.zip.value.length < 12 ) {
    alert("Please fill in field Postal Code. You should only enter 7 characters");
    myform.zip.focus();
    return false;
}

功能:

function okNumber(myform) {
  var regex = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
  if (regex.test(myform.zip.value) == false) {
    alert("Input Valid Postal Code");
    myform.zip.focus();
    return false;
  }

  return true;
}

问题

虽然代码正在执行,但它根本不起作用。 当我运行它时,我得到:

请填写邮政编码字段。您只能输入 7 个字符

一个有效的邮政编码示例是T2X 1V4

【问题讨论】:

  • {1} 业务毫无意义。无论如何,[] 字符类已经是隐式的{1}。与\d 和任何其他匹配单个字符的东西相同。除此之外,这怎么行不通?您是否检查过输入没有前导/尾随空格?
  • 有效加拿大邮政编码的规则是什么?此正则表达式在哪些测试输入上失败?
  • 我没有看到 okNumber 在第一个代码块的任何地方被调用...这段代码正在执行吗?

标签: javascript regex validation postal-code


【解决方案1】:

工作演示

下面是 HTML 验证示例。

function validate(zipInput) {
   var isValid = hasMinimumInput(zipInput) && okNumber(zipInput);
   indicate(isValid);
}

function hasMinimumInput(zipInput) {
  if (zipInput.value == ""
   || zipInput.value == null
   || zipInput.value == "Postal Code"
   || zipInput.value.length < 7 ) { // 7 instead 12 as min
   
      alert("Please fill in field Postal Code. You should only enter 7 characters");
      zipInput.focus();
      return false;
  }
  
  return true;
}

function okNumber(zipInput) {
  var regex = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
  if (regex.test(zipInput.value) == false) {
  
    alert("Input Valid Postal Code");
    zipInput.focus();
    return false;
  }

  return true;
}

function indicate(isValid) {
   document.getElementById("indicateValid").style.display = isValid ? "inline" : "none";
   document.getElementById("indicateInvalid").style.display = isValid ? "none" : "inline";
}
<h1>Canadian Postal Code</h1>
<form name="myform" onSubmit="validate(this.zip); return false;">
  Postal Code: <input type=text" name="zip"></input>
  <button type="submit">Validate</button>
  
  <span style="color:green;" id="indicateValid">valid</span>
  <span style="color:red;" id="indicateInvalid">invalid</span>
  <br/>valid Example: <code>T2X 1V4</code>
</form>
(注:真实提交被return false;禁用)

问题

已经answered by Bill the Lizard

  • 给定if 测试最小长度12 而不是7

固定:

  if (zipInput.value == ""
   || zipInput.value == null
   || zipInput.value == "Postal Code"
   || zipInput.value.length < 7 ) { // not 12 as min
   
      alert("Please fill in field Postal Code. You should only enter 7 characters");
      zipInput.focus();
      return false;
  }

【讨论】:

    【解决方案2】:

    为您解答,希望对您有所帮助。感谢您的宝贵时间

    string[] inputName = new string[5];
        string[] inputId = new string[5];
        string[] inputMarks = new string[5];
    
        Regex StudentId = new Regex(@"\d\d\d\d\d$");
        Regex Marks = new Regex(@"\d\d$");
        Regex StudentName = new Regex(@"^([a-zA-z\s]{5,10})$");
    
        private void btnClear_Click(object sender, EventArgs e)
        {
            rtShowAll.Clear();
    
        }
    
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string Name = txtLastName.Text;
            string id = txtStudentId.Text;
            string marks = txtMarks.Text;
    
            if ((Name == "") || (!StudentName.IsMatch(Name)))
            {
                MessageBox.Show("space cannot be empty and enter valid characters only");
            }
    
            else if (Name != "")
            {
                if ((id == null) || (StudentId.IsMatch(id)))
                {
                    MessageBox.Show("Enter valid id");
                }
                else if ((id != null) || (StudentId.IsMatch(id)))
                {
                    if ((marks == null) || (!Marks.IsMatch(marks)))
                    {
                        MessageBox.Show("enter valid marks");
                    }
    
                    else if ((marks != null) || (Marks.IsMatch(marks)))
                    {
                        for (int i = 0; i <= 5; i++)
                        {
                            inputName[i] = Name;
                            inputId[i] = id;
                            inputMarks[i] = marks;
                            break;
                        }
                    }
    
                }
            }
            txtLastName.Clear();
            txtMarks.Clear();
            txtStudentId.Clear();
    
        }
    
        private void btnShowAll_Click(object sender, EventArgs e)
        {
    
    
            string result = "";
            for (int i = 0; i <= 5; i++)
            {
                result = inputName[i] + "   " + inputId[i] + "   " + inputMarks[i];
                rtShowAll.Text = result;
                break;
            }
    
           //list.Add(rtShowAll.Text);
            //string Showall = "";
           // foreach (string s in list)
          // {
           //    Showall += s + " "+ "\n";
            //}
           // rtShowAll.Text = Showall;
        }
    
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string searchId = txtStudentId.Text;
            string result = "";
    
            txtStudentId.Text = searchId;
    
            for (int i = 0; i < 5; i++)
            {
                if (searchId == inputId[i])
                {
                    result = inputName[i] + "    " + inputMarks[i];
                    rtSearch.Text = result;
                }
                else if (searchId != inputId[i])
                {
                    MessageBox.Show("Enter valid Student id");
                }
            }
        }
    
        private void btnModify_Click(object sender, EventArgs e)
        {
            string id = txtStudentId.Text;
            string newmarks = "";
    
            for (int i = 0; i < 5; i++)
            {
                if (id == inputId[i])
                {
                    newmarks = txtMarks.Text;
                    if ((newmarks == null) || (!Marks.IsMatch(newmarks)))
                    {
                        MessageBox.Show("enter valid marks");
                    }
                    else if ((newmarks != null || (Marks.IsMatch(newmarks))))
                    {
                        inputMarks[i] = newmarks;
                        MessageBox.Show("marks has been modified");
                    }
                }
            }
        }
    }
    

    }

    【讨论】:

    • 请解释您为 OP 编写的代码
    【解决方案3】:

    这适用于加拿大邮政编码:

    /^[a-z][0-9][a-z][- ]?[0-9][a-z][0-9]$/i
    

    它将允许带有空格或连字符的正确 X#X #X# 格式。

    【讨论】:

      【解决方案4】:

      这是我使用的加拿大邮政编码的有效表达方式。 它将严格格式化为 A0A 0A0。

      /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/
      

      【讨论】:

        【解决方案5】:

        这里是规则 http://en.wikipedia.org/wiki/Postal_code#Reserved_characters

        ABCEGHJKLMNPRSTVXY <-- letter used 
        DFIOQU <-- letters not used because it mixes up the reader
        WZ     <-- letters used but not in the first letter
        With that in mind the following in the proper regex
        
        @[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][\s][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]
        

        【讨论】:

          【解决方案6】:

          这适用于所有加拿大邮政编码..

          ^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
          

          【讨论】:

            【解决方案7】:

            第一个错误是初始 if 语句中的最后一个条件。 myform.zip.value.length &lt; 12 应该始终为 true,因此您的这部分代码将始终提醒消息 "Please fill in field Postal Code. You should only enter 7 characters" 并将焦点返回到 zip 字段。由于有效的邮政编码最多包含 7 个字符,因此应将其更改为 myform.zip.value.length &gt; 7

            进行更正后,您在 cmets 中提供的邮政编码 T2X 1V4 将生效。但是,您使用的正则表达式可以简化(如 cmets 中也提到的)。您可以删除 {1} 的所有实例,因为它们是多余的。您可能还打算用? 而不是* 跟随空格。 ? 表示前面的字符或表达式可以出现 0 或 1 次,而 * 表示它可以出现 0 次或 更多 次。我认为您的邮政编码中最多需要一个空格。

            这是我测试过的完整工作代码:

            <!doctype html>
            <html>
            <head>
                <title>JavaScript Regex Tester</title>
                <meta charset="utf-8">
                <script>
                    function validate(myform) {
                        if (myform.zip.value == "" || myform.zip.value == null || myform.zip.value == "Postal Code" || myform.zip.value.length > 7 ) {
                            alert("Please fill in field Postal Code. You should only enter 7 characters");
                            myform.zip.focus();
                            return false;
                        }
            
                        return okNumber(myform);
                    }
            
                    function okNumber(myform) {
                        var regex = /^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$/;
                        if (regex.test(myform.zip.value) == false) {
                            alert("Input Valid Postal Code");
                            myform.zip.focus();
                            return false;
                        }
            
                        return true;
                    }
                </script>
            </head>
            <body>
                <form action="#" name="myform" method="post">
                    <input type="text" name="zip" value="Postal Code" />
                    <input type="button" value="Submit" onclick="validate(document.myform);"/>
                </form>
            </body>
            </html>
            

            最后一点,通常当您在正则表达式中看到[A-Z] 时,至少应该考虑一下它是否应该是[A-Za-z] 来接受大写或小写字母。我不知道加拿大邮政编码是否属于这种情况,但通常情况下,大多数表单应该接受任一输入并根据需要更正大小写。

            【讨论】:

              【解决方案8】:

              正则表达式方法可以验证format of a Canadian postcode,但不足以保证邮政编码确实存在

              例如:A9A 0A0看起来像一个有效的加拿大邮政编码,但正向分拣区A9Adoesn't actually exist

              您确定不想对官方的邮政编码列表进行某种查找吗?

              【讨论】:

              • 在这种情况下,类似于^[A-Z]\d[A-Z][ ]?\d[A-Z]\d$ will work。如果这个正则表达式在你的程序中不起作用,你可能有一个逻辑错误(真而不是假?),错误地调用了正则表达式代码,或者根本没有调用它。
              猜你喜欢
              • 2015-07-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-03-24
              • 2011-03-28
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多