Javascript - Validation of First and Last Names with upper case letters at the beginning

Asked

Viewed 1,712 times

1

Good evening, you guys, I made a javascript to fix a natural person registration in order to create the pattern Name and Surname, for example, João da Silva.

I got what I wanted when the user typed everything down. However, if the user type everything in high box (JOÃO DA SILVA) javascript does not fix and leaves everything in high box even. I would also like it corrected if it was typed also in high box, in case the user forget the CAPSLOCK turned on.

function formatanome(nome){
	
   var letra, tamanho;
   
   tamanho = nome.length;
   
   for (var i=0; i<tamanho; i++)
   {
	 letra = nome.charAt(i);
      if (letra== " ")
         if ((i+1)<tamanho)
     {
        letra = nome.charAt(i+1).toUpperCase();
        nome = nome.substring(0, i+1);
		nome += letra;
        nome += document.getElementById("nome").value.substring(i+2, tamanho);
     }
   }
   
   if (tamanho>0)
   {
      letra = nome.charAt(0).toUpperCase();
      nome = nome.substring(1, tamanho);      
      nome = letra + nome;
   }
   document.getElementById("nome").value = nome;
}
<html>


<script type="text/javascript" src="js.js"></script>


<form name="dispositivo">NIP<input id="nip" type="text" size="8" onblur="inteiro()"/>

ID<input id="resultado" type="readonly" size="8" />

NOME<input id="nome" type="text" size="40" onblur="formatanome(this.value)"/>
</form>

  • the difficulty is to leave the da minuscule

  • https://i.stack.Imgur.com/jx7Ts.png

  • If an answer solved your problem mark it as acceita, see how in the comment link above and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

  • Using a Regex would not solve your problem in a simpler and more streamlined way?

2 answers

2

For all cases - examples of entries in input

nOME sobREnome,  NOME SOBRENOME, nome sobrenome, etc...

See how it works

function formatanome(nome){

  var nome = document.getElementById("nome").value;

  nome = nome.toLowerCase().replace(/(?:^|\s)\S/g, function(capitalize) { return capitalize.toUpperCase(); });

  document.getElementById("nome").value=nome;

}
<form name="dispositivo">
NOME<input id="nome" type="text" size="40" onblur="formatanome(this.value)"/>
</form>

Explanations

turn everything into minusculas

nome.toLowerCase()

and then replace by returning a new string with all combinations of the replaced pattern (replace or Regexp) by a substituent ( a novaSubStr or a function ).

Syntax of the replace method()

nome.replace(RegExp|substr, novaSubStr|função) 

Simplifying for better understanding:

nome.replace(substituído, substituidor) 

For all cases below I will use as replaced the regex below

//substituído /(?:^|\s)\S/g
  • string replacer BBBB

    nome.toLowerCase().replace(/(?:^|\s)\S/g,'BBBB');
    
  • replacer a função

    The new version of Javascript, ES6, brought new Features and among them a new way to create functions using the operator =>. This new way of working with functions are called Arrow Functions.

    • with implicit return - replacer (X) => X.toUpperCase()

      nome.toLowerCase().replace(/(?:^|\s)\S/g, (X) => X.toUpperCase() );
      
    • no implicit return - replacer (X) => { return X.toUpperCase() }

      nome.toLowerCase().replace(/(?:^|\s)\S/g, (X) => { return X.toUpperCase() } );
      
    • without Arrow Function ES6 - function(X) { return X.toUpperCase() }

      nome.toLowerCase().replace(/(?:^|\s)\S/g, function(X) { return X.toUpperCase(); });
      
    • All three functions do the same thing.

REMARKS:

A - the letter X used in the above cases, it is arbitrary. It could have been, for example, replaced by qqcoisa or capitalize or whatever it is. Example: in case 1

(qqcoisa) => qqcoisa.toUpperCase() or (capitalize) => capitalize.toUpperCase().

B - the regular expression /(?:^|\s)\S/g do global search, getting the first letter after a blank.



And in case the prepositions don’t allow to be capitalized we have

function formatanome(nome){

   var nome = document.getElementById("nome").value;

   nome = nome.toLowerCase().replace(/(?:^|\s)\S/g, function(capitalize) { return capitalize.toUpperCase(); });
  
   var PreposM = ["Da","Do","Das","Dos","A", "E"];
   var prepos = ["da","do","das","dos","a", "e"];

   for (var i = PreposM.length - 1; i >= 0; i--) {
     nome = nome.replace(RegExp("\\b" + PreposM[i].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "\\b", "g"), prepos[i]);
   }

document.getElementById("nome").value=nome;

}
<form name="dispositivo">
NOME<input id="nome" type="text" size="40" onblur="formatanome(this.value)"/>
</form>

0

You can create a capitalization method.

  1. Give an Uppercase for the first character.
  2. this.Slice(1), takes the point with text from second character and gives a Lowercase.
  3. Concatenate the data.
  4. Return data.

Generating a capitalize method for the string class:

String.prototype.capitalize = function () {
    return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}

Application of the method in execution:

// Formata o nome de forma capitalizada.
function formatanome(nome) {
    // Tamanho da string.
    var tamanho;
    tamanho = nome.length;
    // Se texto for maior que 1 posição deixa tudo em minúsculas e coloca a primeira letra em maiúsculas.
    if (tamanho > 1) {
        nome = nome.capitalize();
    } else {
        nome = nome.toUpperCase();
    }
    // Devolve o valor capitalizado caso ele seja maior que 1 posição.
    document.getElementById("nome").value = nome;
}

Browser other questions tagged

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