Search code examples
javascriptreactjsregexregexp-replace

regex for name validation without whitespace at beginning in js


I want to validate the input value using regex. The value should be string without white space at the beginning. But accept space in the middle. This value only accepts alphabets.

Example:

"  abcde" -> not accepted
"abcdef lksfksl" -> accepted
"asma124" -> not accepted
"abcde" -> accepted
"abce,./()$#%"-> not accepted

I tried a couple of regEX.

/^[A-Za-z][A-Za-z-\s]*$/ - When I want to delete all alphabets from input last one alphabet is not deleted. If my value is abcde, then a is not deleted when I clicked the delete button.

^[A-Za-z\s]*$ - Empty string is accepted. " abcde" is accepted

/^[^\s].+[a-zA-Z]+[a-zA-Z]+$/ - No alphabet is showing in my input field when I am typing.

I don't understand how to achieve it.


Solution

  • You can achieve this by using this RegExp : /^[a-zA-Z]+[a-zA-Z\s]*?[^0-9]$/

    Explanation :

    ^ Start of string
    [a-zA-Z]+ Matches 1 or more alphabets (Both Lower case and Upper case)
    [a-zA-Z\s]*? Optionally matches alphabets and whitespace character.
    [^0-9] Will not accept the numeric values
    $ End of string

    Live Demo :

    const regExp = /^[a-zA-Z]+[a-zA-Z\s]*?[^0-9]$/;
    
    console.log(regExp.test('  abcde')); // false
    console.log(regExp.test('abcdef lksfksl')); // true
    console.log(regExp.test('asma124')); // false
    console.log(regExp.test('abcde')); // true
    console.log(regExp.test('abce,./()$#%')); // false