Validate inputs in form with regular expressions

Asked

Viewed 1,104 times

2

I have Contacts field on the page where the user must fill, for example, the name, it should only type letters, in the phone field, only numbers and email required the use of "@". 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 user input, but 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 regular expression and then uses it in validation.

Could someone help me? Or is there another way to validate this?

2 answers

1


I gave another similar answer but for credit cards. The interesting idea there is the organization of code, 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!')
});

  • 1

    AMAZING! AMAZING! Thank you so much

0

To validate the name you can use this regex:

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

On the phone

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

And to email

/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
  • It doesn’t work because the browser seems to interpret the variable as a string...

  • When you add the.log console inside IF and ELSE, I can see user inputs comparing to the variable. It only reads "Okay" if I type / [ p{L} s]+$. not as a regular expression.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.