Ilia Tapia
Ilia Tapia

Reputation: 649

Pattern validation expression, first letters capital in angular?

I am working with an input field and I want the user first letter to be capital. Before this, I needed a pattern that allows the user to put the only uppercase letter for that I used

pattern="[A-Z ]*"

Is there any pattern to check if the first letter of the user is capital. The result I want is :

testing => is wrong
Testing => is good.
Testing Done =>is good also.

Upvotes: 1

Views: 6746

Answers (2)

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

Can use /^[A-Z].*$/.

^[A-Z] It mandates that the string should start with a capital letter.

.*$ will now match anything except new lines.

let regex = /^[A-Z].*$/
let str1 = 'testing'
let str2 = 'Testing'
let str3 = 'Testing Done'

console.log(regex.test(str1))
console.log(regex.test(str2))
console.log(regex.test(str3))

If you don't want to have capital letters in between the words then you can try:

 /^([A-Z][a-z]*((\s[A-Za-z])?[a-z]*)*)$/

let regex = /^([A-Z][a-z]*((\s[A-Za-z])?[a-z]*)*)$/

let str1 = 'testing'
let str2 = 'Testing'
let str3 = 'Testing Done'
let str4 = 'TesTing';
let str5 = 'Testing Done Done Done done';

console.log(regex.test(str1))
console.log(regex.test(str2))
console.log(regex.test(str3))
console.log(regex.test(str4))
console.log(regex.test(str5))

Note: To use the pattern in angular you need to escape the backslash. SO you pattern will be something like:

Validators.pattern('^([A-Z][a-z]*((\\s[A-Za-z])?[a-z]*)*)$')

See an example here: https://stackblitz.com/edit/angular-3s3cdc?file=src%2Fapp%2Fapp.component.html

Upvotes: 7

Jagan Mohan Bishoyi
Jagan Mohan Bishoyi

Reputation: 66

regexp = /^[A-Z]/

You can use the above code to validate your string.

Upvotes: 0

Related Questions