0

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 last name (S) is upper case? I want to return true if it matches and false if it doesn't match.

I have been finding solutions that say to try the RegExp ^[A-Z][a-z]*(-|\s)[A-Z][a-z]*$, but I don't know how to use it.

Thanks :)

  • 1
    You might use your [regex](https://regex101.com/r/hSSuya/1) and use [test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) as in this [fiddle](https://jsfiddle.net/sv7ns7uh/) – The fourth bird Mar 12 '18 at 16:35
  • Don't validate names. But anyway: `^[A-Z][A-Za-z]*(?:[\s-][A-Z][A-Za-z]*)+$` – ctwheels Mar 12 '18 at 17:42

3 Answers3

0

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.

David
  • 5,877
  • 3
  • 23
  • 40
-1

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();});
}
Damien Christophe
  • 115
  • 1
  • 1
  • 10
-1

Use a simple css to capitalize your input:

input {
  text-transform: capitalize;
}

<input type="text" name="textfield">
standby954
  • 209
  • 1
  • 7