How I fixed a Regular Expression issue in JavaScript when it worked in PHP

Steve Sohcot
Nov 1, 2020

I had to validate a username in both JavaScript and PHP, and I wanted to use the same Regular Expression for both. With PHP, I had no trouble:

var reg = new RegExp("^[a-zA-Z0–9._-]{3,16}$");

When I copied it into the JavaScript through, it didn’t work. The problem was that even though I defined the “set” (criteria) I had to also include the minimum/maximum number of characters it should match. It worked as soon as I added in a {3,16} at the end.

Like this style of writing? 👍👍 Interested in creating a PHP web application and already know what a “variable” is and the concept of an “if” statement? Check out my book: Web Development for Intermediate Programmers — with PHP

--

--