Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Asking user for home address using Regex

I want to make a prompt asking a user for a valid home address using regex.

I have tested the regex im using on regex101.com but the code still doesnt work no matter what I write…

Example of address that should pass: 26 John Street, City Road

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What have I done wrong?

function button1() {
let address = prompt("Please enter your address");
var regex = /[\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St).?]/;

  if (regex.test(address)) {
    return true;
  } else {
    console.log("Please enter a valid address");
    return false;

  }
}

>Solution :

I think you shouldn’t have the whole expression inside [ and ]

That causes it not to be a sequence of symbols to be expected one-after-the-other, but rather a set of alternatives (which I don’t think is what you intended).

So try this:

function button1() {
  //  let address = prompt("Please enter your address");
  const address = "26 John Street, City Road"

  var regex = /\d+[ ](?:[A-Za-z0-9.-]+[ ]?)+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St).?/;

  if (regex.test(address)) {
    console.log("Valid")
    return true;
  } else {
    console.log("Please enter a valid address");
    return false;

  }
}

button1()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading