Home > Mobile >  Checking input in javascript to see if it matches a Canadian postal code
Checking input in javascript to see if it matches a Canadian postal code

Time:09-28

I'm creating a form for getting information about the user in html and javascript and I am struggling to check if one of my text box inputs is in a specific format.

The format is: ### ###

Where each # is either a letter or a number, an example of this would be N3H 2E9.

My input is from a regular html text box that is being converted into a const within my javascript and I'm wondering if there is a way to validate that the input is in the same format as previously mentioned. I'm pretty new to html and javascript so if you answer please could you provide a small explanation behind your answer?

CodePudding user response:

You can use Regular Expressions (RegEx) to do what you want.

const correctInput = "N3H 2E9";
const incorrectInput = "N3H 2Ea";

const isValid = (input) => /^[0-9A-Z]{3} [0-9A-Z]{3}$/.test(input);

console.log(isValid(correctInput));
console.log(isValid(incorrectInput));

/^[0-9A-Z]{3} [0-9A-Z]{3}$/
  • ^: Matches start of the string
  • [0-9A-Z]{3}: Matches exactly three characters which are one of uppercase A-Z or digits 0-9
  • : Matches space
  • $: Matches end of the string

CodePudding user response:

function validateForm() {
  var postalCode = document.getElementById("postal_code").value;
  // This solution uses a regular expression to test the input for our desired format
  // for more info on what this pattern means exactly, check out
  // https://regex101.com/?regex=^[A-Z0-9]{3} [A-Z0-9]{3}$
  var rgx = /^[A-Z0-9]{3} [A-Z0-9]{3}$/;
  var isValid = rgx.test(postalCode);
  var resultElement = document.getElementById("result");
  if (isValid) {
    resultElement.innerText = "Valid"
  } else {
    resultElement.innerText = "Invalid"
  }
}
<input type="text" id="postal_code">
<button onclick="validateForm()">Validate</button>
<span id="result">Invalid</span>

CodePudding user response:

This is most easily accomplished using a regular expression. A regular expression defines a pattern of characters that input can be tested against. In javascript you can create one as follows:

const expression = /test/

expression is now a regular expression and you can use it to validate strings (in this case, testing whether a part of it contains "test"):

expression.test("Hello") // false
expression.test("test") // true
expression.test("Hello this is a test") // true
expression.test("Hey I'm testing") // true
expression.test("t est") // false
expression.test("Test") // false

Regular expressions can contain special selectors that define not a literal string ("test" for example) but a range of allowed characters. In your example you want to test against numbers and capital letters. That can be notated as [A-Z0-9] meaning "any character between A and Z or between 0 and 9". You want three of those, which can be notated as [A-Z0-9][A-Z0-9][A-Z0-9] or simply as [A-Z0-9]{3}. The final expression would look like:

const expression = /^[A-Z0-9]{3} [A-Z0-9]{3}$/

Note the special characters ^ and $. They correspond with the beginning and ending of a string, ensuring you're not matching any string merely containing a postal code, but only strings exclusively containing a postal code.

Finally, you could write this function as follows:

const isCanadianPostalCode = input => /^[A-Z0-9]{3} [A-Z0-9]{3}$/.test(input);

console.log( isCanadianPostalCode('N3H 2E9A') ) // false
console.log( isCanadianPostalCode('N3H 2E9') ) // true
  • Related