13

I have written a JavaScript to validate Canadian Postal Codes using regex.

However, it does not seem to be working:

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

Problem

It doesn't work at all, although code is executing. When I run it, I get:

Please fill in field Postal Code. You should only enter 7 characters

An example valid postal code would be T2X 1V4.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Alex Block
  • 315
  • 1
  • 4
  • 15
  • the `{1}` business is pointless. A `[]` character class is already an implicit `{1}` anyways., same with `\d` and any other thing that matches single characters. Beyond that, how is this not working? Have you checked that the input doesn't have leading/trailing whitespace? – Marc B Jun 22 '12 at 03:09
  • 2
    What are the rules for a valid Canadian postcode? What test inputs does this regex fail on? – Li-aung Yip Jun 22 '12 at 03:11
  • I don't see okNumber being called anywhere in the first block of code... is this code executing? – kad81 Jun 22 '12 at 03:19

8 Answers8

8

this will work for all canadian postal codes..

^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
Balram Singh
  • 1,576
  • 19
  • 30
4

A regex approach can validate the format of a Canadian postcode, but it's not sufficient to guarantee that the postcode actually exists.

For example: A9A 0A0 looks like a valid Canadian postcode, but the forward sortation area A9A doesn't actually exist.

Are you sure you wouldn't rather do some kind of lookup against an official list of postcodes?

Li-aung Yip
  • 12,320
  • 5
  • 34
  • 49
  • 3
    In that case, something like `^[A-Z]\d[A-Z][ ]?\d[A-Z]\d$` [will work](http://regexr.com?31b0q). If this regex doesn't work in your program, you may have a logic error (true instead of false?), be calling the regex code wrongly, or not calling it at all. – Li-aung Yip Jun 22 '12 at 03:26
3

Here are the rules 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]
user3111634
  • 81
  • 1
  • 1
1

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.

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 more times. I think you want at most one space in your postal codes.

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
1

This is a valid expression for a Canadian Postal Code that I use. It will format strictly as A0A 0A0.

/^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/
Jessica Mather
  • 133
  • 1
  • 11
0

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.

0

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

}

Alexander
  • 1
  • 1
0

Working Demo

For an example of validation in HTML try below.

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>
(Note: real submission is disabled by return false;)

Issue

As already answered by Bill the Lizard:

  • given if tested for min length 12 instead of 7

Fixed:

  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;
  }
hc_dev
  • 8,389
  • 1
  • 26
  • 38