-1

I have written the regex pattern for restricting white space at the start but it is not working. Guide me in finding where I need to change the logic?

^[^\s]+[a-z-A-Z]$

I need to do this in java-script to validate the input field. I need to allow all character in the input field without white space at start and I need all white space at the end and intermediate.

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
Manikandan
  • 51
  • 1
  • 11

1 Answers1

1

A [^\s] matches any char but a whitespace while you want to allow only letters and spaces.

Use

^[a-zA-Z][a-zA-Z\s]*$

NOTE: to also "allow" (=match) any printable ASCII chars other than space, letters and digits you may add [!-\/:-@[-{-~]` to the regex (please refer to this answer of mine):

^[a-zA-Z][a-zA-Z\s!-\/:-@[-`{-~]*$

See the regex demo and a regex graph:

enter image description here

Or, if an empty string should be matched, too:

^(?:[a-zA-Z][a-zA-Z\s]*)?$

Note that to include a hyphen to the character class, it is much safer (and more portable) to place it at the start/end of the character class, i.e. use [a-zA-Z-] instead of [a-z-A-Z].

Details

  • ^ - start of a string
  • [a-zA-Z] - an ASCII letter
  • [a-zA-Z\s]* - 0 or more ASCII letters or whitespaces
  • $ - end of string.

(?:...)? is an optional non-capturing group that matches its pattern 1 or 0 times.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • need to allow spacial character also. – Manikandan Jun 21 '19 at 07:47
  • @Manikandan What chars are special for you? Please check [this anwer of mine](https://stackoverflow.com/a/32311188/3832970) and I think you will be able to adjust this regex on your own. Else, add more details to the question – Wiktor Stribiżew Jun 21 '19 at 07:48
  • thanks i have tried your pattern it is working i have added my special character in my pattern ^[a-zA-Z0-9][a-zA-Z!@#$%^&*?(){}\s]*$ – Manikandan Jun 21 '19 at 08:00