Home > Mobile >  Make a test false by not repeating numbers regex
Make a test false by not repeating numbers regex

Time:03-24

I have a string I'm testing that I need to test false.

test("test_pin_with_numbers", () => {


expect(isValidPin("1111")).toBe(false);
});

along with some other tests this one is throwing me off. How can i test against a repeating number?

So far this code passes/fails all tests except "1111" this needs to be false whilst not effecting a pass for "1234"

const isValidPin = (pin) => {


return /^(\d{4})/g.test(pin);
};

CodePudding user response:

Try this: /(?:(\d)(?!\1)){4}/gm

let pattern = /(?:(\d)(?!\1)){4}/gm

console.log(pattern.test(1234))
console.log(pattern.test(12345))
console.log(pattern.test(1134))
console.log(pattern.test(1111))
console.log(pattern.test(6789))

You can use negative lookahead to make sure a digit is not repeated. And groups to control the length of the pin.

Test regex here: https://regex101.com/r/SdIcYl/1

CodePudding user response:

You can use this regex:

/^((?<number>\d)(?!\d*?\k<number>)){4}$/

Explanation:

^ - match from start of string

( - start a group to repeat

(?<number>\d) - make a group called number matching one digit

(?!\d*?\k<number>) - negative look ahead for zero or more digits followed by the value of number

){4} - repeat the match 4 times

$ - match the end of string

This will match only if the four digits are different.

CodePudding user response:

Unfortunately, the question leaves a few details to be answered. My answer assumes the OP wants to exclude the case of four identical numbers to be used as a pin. All other four-number combinations are deemed to be acceptable.

const isValidPin = (pin) => {

return /^(\d{4})$/.test(pin) && !(/(.)\1\1\1/.test(pin))

};

"12345,1234,2234,4444,1111,1232".split(",").forEach(pin=>console.log(pin ": " isValidPin(pin)))

  • Related