-2

I would like to force the input value of a text field to comply with a specific format. It needs to be capitalized and with no numbers allowed.

I would like this event to fire on onKeydown().

Examples:

Lionel MESSI => Lionel Messi
LiONEL MesSI => Lionel Messi

Neymar JR => Neymar Jr
Neymar 22 JR => Neymar Jr

Franck D'HONNEUR => Franck D'Honneur

Kevin PEREZ ROBERTO => Kevin Perez Roberto 
Chris
  • 57,622
  • 19
  • 111
  • 137
Steffi
  • 6,835
  • 25
  • 78
  • 123

2 Answers2

2

There is no simple one-liner way of doing this. However, you can make a function which can format the name for you.

Originally taken from this answer, I've modified it slightly to reflect your desired output:

var name1 = "Lionel MESSI";
var name2 = "LiONEL MesSI";
var name3 = "Neymar JR";
var name4 = "Neymar 22 JR";
var name5 = "Franck D'HONNEUR";
var name6 = "Kevin PEREZ ROBERTO";

function toTitleCase(str) {
  return str.replace(/\w\S*/g, function(txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  }).replace(/[0-9]/g, '');
}

console.log(toTitleCase(name1));
console.log(toTitleCase(name2));
console.log(toTitleCase(name3));
console.log(toTitleCase(name4));
console.log(toTitleCase(name5));
console.log(toTitleCase(name6));

You may want to check out toUpperCase() and toLowerCase() from the MDN documentation.


To get this functionality in on onKeyDown(), you can use jQuery like the snippet below. I do advice against onKeyDown() though as this creates a weird user experience. Try onBlur instead.

function toTitleCase(str) {
  return str.replace(/\w\S*/g, function(txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  }).replace(/[0-9]/g, '');
}

$("#name").on("keydown", function() {
  $(this).val(toTitleCase($(this).val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Name: <input id="name">
Community
  • 1
  • 1
Chris
  • 57,622
  • 19
  • 111
  • 137
0

With the help of a little helper function from this question: How do I make the first letter of a string uppercase in JavaScript?

I wrote a quick script that fires on input blur:

$(document).ready(function() {
    function capitalizeFirstLetterOfEachWord(string) {
        strArr = string.split(' ');
        resArr = [];
        for(i=0;i<strArr.length;i++){
            resArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1);
        }
        return resArr.join(" ");
    }

    $('.forceCapital').blur(function(e) {
        $(this).val(capitalizeFirstLetterOfEachWord($(this).val()));
    });
});

https://jsfiddle.net/sa2ox30d/2/

Community
  • 1
  • 1
symlink
  • 11,984
  • 7
  • 29
  • 50