javascript 验证加拿大邮政编码正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11149678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validate Canadian Postal Code Regex
提问by Alex Block
I have a script written in JavaScript to Validate Canadian Postal Codes using Regex, however it does not seem to be working. Here is the script:
我有一个用 JavaScript 编写的脚本来使用正则表达式验证加拿大邮政编码,但它似乎不起作用。这是脚本:
If statement:
如果语句:
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:
功能:
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;
}
回答by Balram Singh
this will work for all canadian postal codes..
这将适用于所有加拿大邮政编码..
^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
回答by Li-aung Yip
A regex approach can validate the formatof a Canadian postcode, but it's not sufficient to guarantee that the postcode actually exists.
正则表达式方法可以验证加拿大邮政编码的格式,但不足以保证邮政编码确实存在。
For example: A9A 0A0
lookslike a valid Canadian postcode, but the forward sortation area A9A
doesn't actually exist.
例如:A9A 0A0
看起来像一个有效的加拿大邮政编码,但A9A
实际上不存在前向分拣区。
Are you sure you wouldn't rather do some kind of lookup against an official list of postcodes?
您确定您不想对官方邮政编码列表进行某种查找吗?
回答by user3111634
Here are the rules http://en.wikipedia.org/wiki/Postal_code#Reserved_characters
以下是规则 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]
回答by Jessica Mather
This is a valid expression for a Canadian Postal Code that I use. It will format strictly as A0A 0A0.
这是我使用的加拿大邮政编码的有效表达式。它将严格格式化为 A0A 0A0。
/^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/
回答by Creeperstanson
This will do for Canadian postal code:
这将适用于加拿大邮政编码:
/^[a-z][0-9][a-z][- ]?[0-9][a-z][0-9]$/i
It will allow for the proper X#X #X# format with a space or hyphen.
它将允许带有空格或连字符的正确 X#X #X# 格式。
回答by Alexander
Solution for you answer, it will help i hope. Thanks for your time
您的答案的解决方案,我希望它会有所帮助。谢谢你的时间
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");
}
}
}
}
}
}
}
回答by Bill the Lizard
The first error is the last condition in your initial if statement. myform.zip.value.length < 12
should always be true, so this part of your code will always alert the message "Please fill in field Postal Code. You should only enter 7 characters"
and take focus back to the zip
field. Since a valid postal code has a maximum of 7 characters, this should be changed to myform.zip.value.length > 7
.
第一个错误是初始 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
.
After making that correction, the postal code T2X 1V4
that you provided in the comments validates. However, the regular expression you used can be simplified (as was also mentioned in the comments). You can remove all instances of {1}
since they're redundant. You probably also meant to follow the space with a ?
instead of a *
. A ?
means that the previous character or expression can appear 0 or 1 time, while a *
means that it can appear 0 or moretimes. I think you want at most one space in your postal codes.
进行更正后T2X 1V4
,您在评论中提供的邮政编码将生效。但是,您使用的正则表达式可以简化(正如评论中也提到的)。您可以删除所有实例,{1}
因为它们是多余的。您可能还打算用 a?
而不是 a来跟在空格后面*
。甲?
意味着先前的字符或表达式可以出现0或1的时间,而*
它可以出现0或手段更多次。我认为您最多希望邮政编码中有一个空格。
Here's the full working code that I tested this with:
这是我测试的完整工作代码:
<!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>
One final note, usually when you see [A-Z]
in a regular expression it's worth at least considering whether it should be [A-Za-z]
to accept either upper or lower case letters. I don't know if this is the case for Canadian postal codes, but it usually is the case that most forms should accept either input and correct the case as needed.
最后一点,通常当您[A-Z]
在正则表达式中看到时,至少值得考虑是否应该[A-Za-z]
接受大写或小写字母。我不知道加拿大邮政编码是否是这种情况,但通常情况下,大多数表单应该接受任一输入并根据需要更正大小写。