What is the best way to ensure that at least one of the two user inputs matches the specified regex pattern?

I am facing a challenge with regular expressions for zip codes from two different countries - The Netherlands and Belgium.

For The Netherlands:

.match(/^[1-9][0-9]{3} ?(?!sa|sd|ss)[A-Za-z]{2}$/g)

For Belgium:

.match(/^[1-9]{1}\d{3}$/g)

Users should be able to input either a Dutch zip code or a Belgian zip code, such as 1111 AA (Netherlands) or 1111 (Belgium). I have been attempting to create a regex pattern to allow for either input, but I haven't been successful so far.

This is my current attempt:

.match(/^(?:[1-9]{1}\d{3}) | ([1-9][0-9]{3} ?(?!sa|sd|ss)[A-Za-z]{2}$)/g)

However, this pattern seems to be causing issues and doesn't validate either of the two types of zip codes. Could it be that I am not using the OR operator correctly?

Answer №1

It appears that there may be a mistake with the spaces surrounding the alternation in your expression. However, you can simplify it by using an optional non-capture group instead:

^[1-9]\d{3}(?: ?(?!s[ads])[A-Z]{2})?$

For a demonstration, check out this demo


  • ^ - Denotes the start of the line;
  • [1-9]\d{3} - Matches a digit from 1 to 9 followed by three more digits;
  • (?: - Begins a non-capturing group;
    • ?(?!s[ads]) - A space character followed by a negative lookahead to ensure the position is not followed by 's' with 'ads';
    • [A-Z]{2} - Matches two alphabetical characters;
    • )? - Ends the non-capture group and makes it optional;
  • $ - Denotes the end of the line.

Please note that this matching process is case-insensitive.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript troubleshooting: Confusion with Radiobuttons and Checkboxes 'checked' status

My Javascript code utilizes JQuery to generate quizzes with free text, radio buttons (single choice), and check boxes (multiple choice) questions. These quizzes are created using a web interface styled with Zurb - Foundation and serialized in JSON format. ...

Identifying functions that contain dots in their names using JSHint

While running jshint on a JavaScript file, I encountered functions with dots in their names for namespacing purposes. Specifically, within the d3 library, there is a significant portion of code that resembles: d3.select("something") Should I simply disab ...

What is the best way to create a new browser window for a pop-up?

Using the following JavaScript code will open a popup: window.open('http://www.google.com','mywindow','width=400,height=200'); If you call it two times like this: window.open('http://www.google.com','mywindow ...

What steps do I need to follow in order to properly execute this HTTP request?

Recently, I came across this amazing tool called SimplePush.io that is perfect for one of my projects. It works flawlessly via curl, as shown on their website: ~ $ curl 'https://api.simplepush.io/send/HuxgBB/Wow/So easy' or ~ $ curl --data &ap ...

Tips for adjusting the current window location in Selenium without having to close the window

I am currently working with seleniumIDE My goal is to have a Test Case navigate to a different location depending on a condition (please note that I am using JavaScript for this purpose, and cannot use the if-then plugin at the moment). I have tried using ...

"Strategies for using Selenium in Python to simulate clicks without relying on class, id, or name attributes

I am currently attempting to locate the "X" button and click on it, but I am struggling to find a way to do so. Below is the HTML code for the element: <div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: ...

When do jQuery.when callbacks trigger when every Deferred is no longer 'unresolved' (resolved or rejected)?

When you pass multiple Deferred objects to jQuery.when, a new "master" Deferred object is returned. This master Deferred object keeps track of the overall state of all the Deferreds it received. Here's how the method works: The master Deferred reso ...

Encountering a problem when trying to pass a PHP array variable to a JavaScript function

I need some help with passing an array and input value from a form to a JavaScript function. The array, $quotes, contains posts. <form method="post"> <p>Search:<input type="text" name="qSearch" id="qSea ...

Unable to render any charts with angular-chart.js

Utilizing the dependency angular-chart.js in my angular project has allowed me to showcase data visualizations on my admin page. Recently, I decided to upgrade angular-chart.js to version 1.1 and Chart.hs to version 2.5 based on the README.md guidelines o ...

Commands for banning or kicking users in discord.js

Basically, I am looking for simple commands that allow me to type: <ban [user here] or <kick [user here] and have it kick/ban the referenced user. I understand this may seem basic, but I am new to Discord bot coding and JavaScript in general. Can a ...

Revise the JSON format to be compatible with a JavaScript template library

My goal is to utilize JSON data for parsing a template using JavaScript. The Mustache library provides a solution as shown below: var output = $("#output"); // template stored in JS var as a string var templateString = '<div>'+ '< ...

Is it recommended to use django's render_to_string response with innerHTML?

This is my first Django project, so please bear with me if I'm making some basic mistakes. I'm currently working on a webpage that will display a report in an HTML table. However, I feel like the process I'm using to gather the data and cons ...

Issue encountered when integrating JavaScript into Django view form update

I have successfully implemented a Django view to add an invoice to my application, complete with added JavaScript functionality that is functioning properly. <p> <label for="id_total_without_vat">Price</label> <input ...

Struggling with React Js and need some assistance?

I'm completely new to React Js and encountering issues with my code. Here's what I have: Here is the content of my script file named Main.jsx. This file gets compiled by React, and the output is stored in main.js under the 'dist' folde ...

Avoid updating the input from ng-model while it is being edited

There are times when my model.field can be altered by both user input into an input field and by other functions running in the background. However, I want to handle situations where changes made by the user take precedence over modifications made by those ...

What is the best way to manage json-parse errors in a node.js environment?

After countless hours of research, I am still unable to find a solution to my seemingly simple and common problem: In Node.js using Express, I want to retrieve JSON-data via http-POST. To simplify the process, I intend to utilize the app.use(express.json( ...

Determining the quantity of items within a div using jQuery

Similar Question: Retrieve the count of elements inside parent div using jQuery Can you determine the total number of elements within a specific div? <div id=count"> <span></span> <span></span> <span></ ...

What is the solution to determining the accurate span form value?

The script below calculates a simple sum, displaying an error if the sum exceeds or falls below 100. Despite the error message, the user can still proceed to the next page. I want to restrict the user from moving to the next page until the sum equals 100 ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...

Are there advantages to incorporating d3.js through npm in an Angular 2 TypeScript project?

Summary: It is recommended to install d3.js via npm along with the typings. The accepted answer provides more details on this issue. This question was asked during my initial stages of learning Angular. The npm process is commonly used for tree-shaking, pa ...