JavaScript regular expression does not work inside the form tag

0
function celular(){var celular=document.getElementById("celular").value;
var ExpReg = /^[0-9]{11}$/;
if(ExpReg.test(celular)){
alert("Sim passou no teste.");
return true;
}
alert("Não passou no teste.");
return false;}

funciona:<input type="text" id="celular" onkeyup="celular();">
não funciona:<form><input type="text" id="celular" onkeyup="celular();"></form>
    
asked by anonymous 12.10.2016 / 04:49

2 answers

3

I believe your intent was to check the field before the form is submitted.

Note that you are working with events . Events relate to who shot you.

In this case it is correct to use onkeyup in the input, since it is firing the event every time a tile "returns" from an insert.

But it has nothing to do with sending form so it is necessary to use another event onsubmit .

Remembering that it relates to the element that triggered it, this way it would not be possible to use the input event in the form, since the this should be input and not form .

In this case you just need to do:

function _celular(){
    var celular = document.getElementById("celular").value;
    var ExpReg = /^[0-9]{11}$/;
    if (ExpReg.test(celular)) {
        alert("Sim passou no teste.");
        return true;
    }
    alert("Não passou no teste.");
    return false;
}
<form onsubmit="_celular()">
  <input type="text" id="celular" onkeyup="_celular()">
  <input type="submit" value="enviar">
</form>

You do not use any tris , but rather a search for element.

    
12.10.2016 / 22:09
0

Try something like this:

  // não use o mesmo nome da função, na variavel 
  // ex: var celular=document.getElementById("celular").value; 
  // function celular() {...}

  var minhasRegex = {
    telefone: /^((\+55)?([1-9]{2})([\d]{8}))$/,
    celular: /^(\+55)?([1-9]{2})([\d]{8,9})$/,
  };

function validaCelular(evento) {
  var texto = evento.target.value;

  if (minhasRegex.celular.test(texto)) {
    alert('Sim passou no teste.');
    return true;
  }
  alert('Não passou no teste.');
  return false;
};

var celularInput = document.getElementById('celular');

// Ou valida quando usuario tirar o foco do elemento
celularInput.addEventListener('blur', validaCelular);

// OU valida a cada keyup: 
celularInput.addEventListener('keyup', validaCelular);
    
13.10.2016 / 01:30