Javascript - Validation of first and last name with capital letters at the beginning

1

Good evening guys, I made a javascript to correct a person's registry in order to create the First and Last name , for example, João da Silva. p>

I got what I wanted when the user types everything in the box. However, if the user types everything in the upper box (JOÃO DA SILVA), the javascript does not correct and leaves everything in the same box.   I would also like it to be corrected if it were also typed in the upper box, in case the user forgets CAPSLOCK 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>
    
asked by anonymous 07.10.2018 / 01:35

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 lowercase

nome.toLowerCase()
  

and then do a replace by returning a new string with all combinations of the replaced pattern (substr or a RegExp) by a substitute (a newSubStr 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 of the following cases, I will replace the regex below

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

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

    The new version of JavaScript, the ES6, has brought new features and among them a new way of creating functions using the => operator. This new way of working with functions is called Arrow Functions .

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

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

      nome.toLowerCase().replace(/(?:^|\s)\S/g, (X) => { return X.toUpperCase() } );
      
    • no 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.

  

COMMENTS:

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

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

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

And if the prepositions are not 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>
    
07.10.2018 / 02:12
0

You can create a capitalization method.

  • Give an UpperCase to the first character.
  • this.slice (1), takes the dot with text from second character and gives a LowerCase.
  • Concatenate the data.
  • Return the data.
  • Generating a method capitalize for the string class:

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

    Applying method at runtime:

    // 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;
    }
    
        
    07.10.2018 / 08:53