Skip to content Skip to sidebar Skip to footer

How To Check If Firstname's And Lastname's First Characters Are Uppercase?

I have an input filed where users will enter their first and last name. For example: (John Smith) How can I check if the first character of first name (J) and first character of la

Solution 1:

There should be a few layers that you should implement.

The first is in your markup, set your input's pattern attribute equal to the following RegEx:

^[A-Z].* [A-Z].*$

The second is in your styling, style the input to include the following:

[selector] {text-transform: capitalize;}

The third is in your JavaScript, change the String from the input to a proper-cased equivalent using the following function that will allow you to convert the input's value in your form's submit event (courtesy of Tuan):

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

Finally, the fourth would be in your back-end code, you would want to re-validate that the input matches the format there too. But since you didn't specify the back-end language, I cannot help you there.

Doing these four things accomplishes a few things. For the average user using your form, they'd input the desired format via the CSS styling. For the malicious user trying to bypass your desired behavior, the newb would just try to remove the pattern attribute only to get caught by the JavaScript. The user with a little more brains would remove the JavaScript only to get caught by the back-end code.


Solution 2:

There is a good and simply answer here

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

Solution 3:

Use a simple css to capitalize your input:

input {
  text-transform: capitalize;
}

<input type="text" name="textfield">

Post a Comment for "How To Check If Firstname's And Lastname's First Characters Are Uppercase?"