Home > Mobile >  REGEX - Check to make sure string has at least two digits, at least two non-alphanumeric characters,
REGEX - Check to make sure string has at least two digits, at least two non-alphanumeric characters,

Time:11-16

I am not very good with regex, and I've tried using a regex generator/debugger, but I can't seem to figure it out. Basically, I want to check and make sure any given string has:

  • At LEAST two digits 0-9. Both (or more than both) can occur anywhere in the string, and can be the same both or different, as long as there is at least two contained in the string.
  • At LEAST two non-alphanumeric characters (!, *, $, #, literally any character on a keyboard excluding letters and numbers since those need checked separately). Both (or more than both) can occur anywhere in the string, and can be the same both or different, as long as there is at least two contained in the string.
  • At least ONE capitol letter
  • At least ONE lowercase letter
  • CANNOT contain ANY whitespace characters
  • Should not discriminate on WHERE in the string any given character is as long as each TYPE of character occurs at least twice.

I couldn't seem to find anything on the internet to this exact thing. Also, it would be a bonus is this checked to make sure the string was at least 8 characters long (as this is for password verification), but I'm checking that manually anyway due to changing textbox colors/errors/etc (for example, a password with less than 8 characters turns the box red, if it's above 8 but less than 16 it's yellow, if it's above 16 it's green). Basically I'm building a two step verification (before form submission and after, the before part is mostly checking to warn the user BEFORE he/she submits a form that will contain invalid data).

CodePudding user response:

You may use positive lookaheads for all the requirements:

^(?=.*\d.*\d)(?=.*[^A-Za-z0-9].*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])\S $

This regex pattern says to match:

  • ^ from the start of the string
  • (?=.*\d.*\d) assert that two (or more) digits are present
  • (?=.*[^A-Za-z0-9].*[^A-Za-z0-9]) assert two symbols
  • (?=.*[A-Z]) assert at least one capital letter
  • (?=.*[a-z]) assert at least one lowercase letter
  • \S match one or more non whitespace characters
  • $ end of the string

Here is a regex demo:

var valid = "#AaBb12$";
var invalid1 = "Aa12$ Z";
var invalid2 = "Aa$";
var re = /^(?=.*\d.*\d)(?=.*[^A-Za-z0-9].*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])\S $/;
console.log(re.test(valid));
console.log(re.test(invalid1));
console.log(re.test(invalid2));

  • Related