Regular expression for password

4

I'm trying to do a strong password check in javascript. Initially I want to check if there are 02 numbers in the string under the following conditions:

  • "12vvv": two consecutive numbers or more of anything returning true
  • "1a1a": two separate numbers or more returning true
  • Should return true in all cases where the text contains 02 numbers or more, regardless of its position.
  • I got the expression below that returns true only in case 2 ("1a1a"):

    /(\d{1}).(\d{1})/.test("a1a1")
    

    But better option was without regular expression:

      function hasTwoNumber(text) {
        var arr        = text.split(""),
            tamanho    = arr.length,
            qtd = 0;
    
        for (var i = 0; i < tamanho; i++) {
          if (/[0-9]/.test(arr[i])) {
            qtd++;
          }
        }
    
        return qtd > 1;
      }
    
    console.log(hasTwoNumber("1a1a")); //true
    console.log(hasTwoNumber("11aa")); //true
    

    I would like to get this same result with regular expression. Does anyone know a regular expression that meets these conditions?

        
    asked by anonymous 22.02.2017 / 20:54

    2 answers

    3

    A different way:

    var a = '1a11aa1'.match(/\d.*\d+/g) != null;
    console.log(a);
    
    var b = 'a1a11'.match(/\d.*\d+/g) != null;
    console.log(b);
    
    var c = '1aaaa1'.match(/\d.*\d+/g) != null;
    console.log(c);
    
    var d = 'aaaa1'.match(/\d.*\d+/g) != null;
    console.log(d);
        
    23.02.2017 / 13:23
    3

    You can use the following regex /\d.\d|\d{2}./ it says that you must marry a number followed by anything and then another number or ( | ) two numbers followed by anything.

    Examples:

    /\d.\d|\d{2}./.test('1bab22') //false, não tem nada depois dos dois números seguidos
    /\d.\d|\d{2}./.test('1b1') //true, casa o primeiro padrão (lado esquerdo)
    /\d.\d|\d{2}./.test('1baaa') //false
    /\d.\d|\d{2}./.test('11') //false
    /\d.\d|\d{2}./.test('111') //true, devido ao ponto casar qualquer coisa
    

    If it is necessary to return false to three consecutive numbers, change the point by \D which means no digit.

    /\d\D\d|\d{2}\D/.test('111') //false
    

    You can identify 2 or more numbers with '2aaaa1a'.match(/\d+/g) , in which case the approach changes from validate to capture and then check to see if it hits as expected.

    var temNumero = '2aaaa1a'.match(/\d+/g);
    if(temNumero.length >=2){
       console.log('válido');
    }else{
       console.log('não atende o padrão');
    }
    
        
    22.02.2017 / 21:15