使用正则表达式验证加拿大邮政编码

Validate Canadian Postal Code using regex

本文关键字:加拿大 邮政编码 验证 正则表达式      更新时间:2023-09-26

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

但是,它似乎不起作用:

JavaScript

If 语句:

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

这将

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

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

正则表达式方法可以验证加拿大邮政编码的格式,但不足以保证邮政编码确实存在

例如:A9A 0A0看起来像一个有效的加拿大邮政编码,但前向分拣区域A9A实际上并不存在。

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

以下是规则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]

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

进行更正后,将在注释中提供的邮政编码T2X 1V4进行验证。 但是,您使用的正则表达式可以简化(如注释中也提到的那样)。 您可以删除所有{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]接受大写或小写字母。 我不知道加拿大邮政编码是否如此,但通常情况下,大多数表格都应该接受输入并根据需要更正大小写。

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

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

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

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

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

解决方案给你答案,我希望它会有所帮助。感谢您抽出宝贵时间

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");
                }
            }
        }
    }
}

}

工作演示

有关 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;禁用)

问题

正如蜥蜴比尔已经回答的那样:

  • 给定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;
  }