skip to Main Content

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-zs]*$ – 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.

4

Answers


  1. Look for a string that starts with a-z, then either immediately ends or is followed by [a-zs]*[a-z]. This ensures the last character is not whitespace.

    Note that if you pass the case-insensitive flag /i, you do not need to type a-zA-Z.

    const testCases = [
    ["  abcde", false],
    ["abcdef lksfksl", true],
    ["asma124", false],
    ["abcde", true],
    ["abcde ", false],
    ["abce,./()$#%", false]]
    
    testCases.forEach(([str,expected])=>{
      console.log(`string: "${str}":
        expected: ${expected}, actual: ${/^[a-z](?:[a-zs]*[a-z]$|$)/i.test(str)}
        `)
    })
    Login or Signup to reply.
  2. So first character is strictly letter, and others are letters or white space.
    + is like greedy character, you might want to switch it for *, but it seems to work as it is.

    /^(w)[a-zA-Z ]+/gm.test(" abcde")

    Login or Signup to reply.
  3. You could write a case insensitive pattern as:

    ^[a-z]+(?:[a-zs]*[a-z])?$
    

    Explanation

    • ^ Start of string
    • [a-z]+ Match 1+ chars a-z
    • (?:[a-zs]*[a-z])? Optionally match chars a-z or whitespace chars followed by a char a-z
    • $ End of string

    Regex demo

    const regex = /^[a-z]+(?:[a-zs]*[a-z])?$/i;
    [
      "  abcde",
      "abcdef lksfksl",
      "asma124",
      "abcde",
      "abce,./()$#%"
    ].forEach(s =>
      console.log(`${regex.test(s)} -- > "${s}"`)
    )
    Login or Signup to reply.
  4. You can achieve this by using this RegExp : /^[a-zA-Z]+[a-zA-Zs]*?[^0-9]$/

    Explanation :

    ^ Start of string
    [a-zA-Z]+ Matches 1 or more alphabets (Both Lower case and Upper case)
    [a-zA-Zs]*? 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-Zs]*?[^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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search