Validate form inputs with regular expressions

1

I have contacts field in the page where the user must fill in, for example, the name, he should just type letters, in the phone field, just numbers and email required to use the "@". The idea is to display a message to the user when they enter number in the "name" field and so on.

I was able to capture the user input, but the regular expression does not work.

This is my code:

var validaNome = $("#input-nome");
validaNome.on("input", function(){
    var digitado = validaNome.val();
    var comparavel = new RegExp("ab+c");

    if(digitado <= comparavel){
        $(".digite-nome").css("display", "none");
    }else {
        $(".digite-nome").css("display", "block");
    };
});

The comparable variable receives the regular expression and then uses it in the validation.

Can anyone help me? Or is there another way to validate this?

    
asked by anonymous 20.06.2017 / 06:09

2 answers

0

I gave another similar reply but for credit cards. The interesting idea there is the code organization, which facilitates reading and development.

You could do it like this:

var inputs = {
  nome: /^[\w\s]+$/,
  telefone: /^[\d\s]+$/,
  email: /^[^@]+@[^@]+\.[^@]+/
};


$("form input").on("change", function() {
  var tipo = this.name;
  var regex = inputs[tipo];

  if (this.value.match(regex)) alert('O campo ' + tipo + ' está válido!');
  else alert('O campo ' + tipo + ' está inválido!')
});
    
20.06.2017 / 11:03
0

To validate the name you can use this regex:

/^[\p{L}\s]+$

To the phone

/(\d{3}|\d{2}|\(\d{2}\))\s*(\d{9}|\d{8})

And for email

/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
    
20.06.2017 / 06:29