Home > Mobile >  Password validation with sequential numbers
Password validation with sequential numbers

Time:09-28

I need to check if has a 2 numbers sequence, if has comes back true, if not false.

example:

113489 //false on 11
123456 // true
189033 // false on 33

Can be with regex or without regex.

CodePudding user response:

I don't know how to do it with regex, so why not just loop over it

var str = "189033";

function check(str) {

  var arr = str.split("");
  var last = null;
  for (var i = 0; i < arr.length; i  ) {
    var digit = arr[i]
    if (digit == last) {
      return false;
    }
    last = digit;
  }
  return true;
}
console.log(check(str))
console.log(check("123456"))

CodePudding user response:

Test for all numbers, and use a negative lookahead for two consecutive identical numbers:

[
  '113489', //false on 11
  '123456', // true
  '189033' // false on 33
].forEach(str => {
  let isValid = /^(?!.*([0-9])\1)[0-9] $/.test(str);
  console.log(str   ' => '   isValid)
});

Result:

113489 => false
123456 => true
189033 => false

Explanation of regex:

  • ^ -- anchor at start of string
  • (?!.*([0-9])\1) -- negative lookahead for a single digit [0-9], followed by the same digit (\1 back references the first capture group)
  • [0-9] -- expect just numbers
  • $ -- anchor at end of string
  • Related