Validating elements of an array in javascript

2

I have the script below where I am not sure how to prevent an entry whose any part of the name is numeric only. Example Fulano de Tal 123 returns 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>
    
asked by anonymous 07.07.2017 / 13:20

2 answers

2

You were comparing .value > 0 and this gives a boolean, so when you do then if(... == 0) this will never be true because 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>
    
07.07.2017 / 13:26
2

I'd advise doing this validation using regex , follow the example below:

* This code validates the name as a whole, so if there is a number in the name you will be prompted 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 only a block of numbers ( Fulano de Tal 123 ), it 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>
    
07.07.2017 / 13:24