Validation of elements of a javascript array

Asked

Viewed 351 times

2

I have the script below which I am not sure how to prevent an entry whose any part of the name is only numeric. Example Fulano de Tal 123 return me valid.

 
function formatar() {
  var nome = document.getElementById("nome").value;
  var partes = nome.split(' ');
  var IsNumericString = partes.filter(function(i){
    return isNaN(i);
  }).length > 0;

  if (IsNumericString == 0 ) {
    alert("Digite seu nome corretamente");
  }else{
    alert("Nome OK");
  }

}
document.querySelector("button").addEventListener('click', formatar);
<input id="nome" type="text" value="Fulano de Tal" />
<button>Formatar</button>

2 answers

1

I advise to do this validation using regex, follow the example:

*This code validates the name as a whole, so if there is a number in the name will ask to type again:

function formatar() {
  var nome = document.getElementById("nome").value;
  var regex = nome.match(/\d+/g);
  if (regex != null) {
    alert("Digite seu nome corretamente");
  } else {
    alert("Nome OK");
  }
}
document.querySelector("button").addEventListener('click', formatar);
<input id="nome" type="text" value="Fulano de Tal" />
<button>Formatar</button>

In this other snippet the parts are validated independently, that is, if there is a block of numbers only(Fulano de Tal 123), asks to type again:

function formatar() {
  var nome = document.getElementById("nome").value;
  var partes = nome.split(' ');
  var isNumeric = false;
  partes.map(function(item) {
    if (/^\d+$/.test(item)) isNumeric = true;
  })
  if (isNumeric) {
    alert("Digite seu nome corretamente");
  } else {
    alert("Nome OK");
  }
}
document.querySelector("button").addEventListener('click', formatar);
<input id="nome" type="text" value="Fulano de Tal" />
<button>Formatar</button>

  • It was really hard to choose which answer I should accept, but I’m a Sergio fan and that says it all :)

  • @Leocaracciolo hahahaha, we are fans =)

1


You were making a comparison .value > 0 and that’s a boolean, so when you do the if(... == 0) This will never come true because the IsNumericString is boolean and not length/numeric.

function formatar() {
  var nome = document.getElementById("nome").value;
  var partes = nome.split(' ');
  var HasNumericStrings = partes.filter(function(i) {
    return !isNaN(i);
  }).length > 0;

  if (HasNumericStrings) {
    alert("Digite seu nome corretamente");
  } else {
    alert("Nome OK");
  }

}
document.querySelector("button").addEventListener('click', formatar);
<input id="nome" type="text" value="Fulano de Tal" />
<button>Formatar</button>

  • Perfect!!!!! alias, as always right!!! It takes advantage and implements this validation also in its answer in this post https://answall.com/questions/218609/pega-a-%C3%Baltima-posi%C3%A7%C3%A3o-de-um-split/

Browser other questions tagged

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