How to detect a certain sequence of numbers in javascript?

0

In the address book field, I have the zip field. In this field cep, I need to do some validations:

1 - Do not allow the user to enter a sequence with two numbers alternating with each other:

EX 1: "12121212"
EX 2: "12312312"

2 - Do not allow the user to enter a sequence of a certain number:

EX: "111111111"

How could I do this? I could not make a regex that would handle both situations.

    
asked by anonymous 02.05.2018 / 14:01

2 answers

1

You can validate the replicates with the following expression: /([0-9]{2,3})/g

It will evaluate if there are groups of 2 or 3 repeated numbers, that is: 1212 or 123123

Example:

var cep = document.querySelector("input[name=cep]");


function fazRegex(){
	var reg = /([0-9]{2,3})/g;
  
 
  if(reg.test(cep.value))
  	document.querySelector("#resultado").innerHTML = "Errado";
  else
  	document.querySelector("#resultado").innerHTML = "Certo";
}

cep.addEventListener("keyup", fazRegex);
<input type="text" name="cep" onkeyup="fazRegex()"/>
<div id="resultado"></div>

See also jsFindle

If you want to test the expression more thoroughly I strongly advise you to visit the site:

regular expressions 101

    
02.05.2018 / 16:10
1

First I created a function to check for duplicates in the string, which works as follows: Check the last string if the numbers contain the repeat (using the previous reference) for the case of repeating 2 numbers.

Then I created one to check for repeated content, where I used a reduce content; I took the first position and checked if all others are equal to it, if so, it returns true ...

In the end I check for the denial of duplicates and all the duplicates exist to be a valid string.

var str1 = "121212122";
var str2 = "111111111";
var str3 = "123456789";

var is_repetidos = function(str) {
  return /([0-9])+/g.test(str);
}

var todos_iguais = function(str) {

  var conteudo_separado = str.split("");

  return conteudo_separado.reduce(function(a, b) {
    return a == b;
  }, str[0]);

}

var is_valid = function(str) {
  return !(is_repetidos(str) || todos_iguais(str));
}

var dados = [str1, str2, str3];

for (var i = 0; i < dados.length; i++) {
  console.log(dados[i] + " = " + is_valid(dados[i]))
}
    
02.05.2018 / 16:00