javaregexvalidationnames

Check if name is valid with Proper case and Max one space


I searched for all regex exp but didn't find any matching my needs.

In none of the above did I get a solution:

I need to check that the name is valid if
=> First letter every word should be caps
=> Rest all letters of each word should be small
=> Name should have only alpha char A-Z and a-z
=> First word Length should be min 3
=> Name should not have more than one space between words

Ex :
sujay => false
Sujay => true

Sujay u => false
Sujay U => true

Sujay U n => false
Sujay U N => true

SuJay U => false
Sujay UN => false
Sujay Uls => true

Sujay9 => false
Su => false
Su U => false
Sujay U N => true
Sujay Uls Nat=> true

|*| Check function used :

static boolean chkNamVldFnc(String namVar)
{
    String namRegExpVar = "[A-Z][A-Za-z ]{2,}";

    Pattern pVar = Pattern.compile(namRegExpVar);
    Matcher mVar = pVar.matcher(namVar);
    return mVar.matches();
}

|*| Try 1 :

String namRegExpVar = "[A-Z][A-Za-z ]{2,}";

|*| Try 2 :

String namRegExpVar = "[A-Z][a-z]{2,}+//s[A-Z][a-z]{2,}";

|*| Try 3 :

String NamRegExpVar = "[A-Z][a-z]{2,}||[A-Z][a-z]{2,}+//s[A-Z][a-z]";

Kindly help me with Proper Regular Exp :

I also want to know why we should start Reg Exp with ^ and end with $


Solution

  • Try:

    ^[A-Z][a-z]{2,}(?: [A-Z][a-z]*)*$