A Gilani
A Gilani

Reputation: 443

Regex for javascript to test strings, number and special characters

I am trying to make a regex to validate a text field in javascript. The condition is that it can contain Characters from a to z (small letters or caps), can include numbers and spaces and the some special characters e.g ()[]’“/.-_&– It cannot start with a space or end with a space.

I have written the following

([A-Za-z0-9\s*\(\)\[\]'"/.\-_&–])

But I am pretty sure it can be improved upon a lot. Can someone help

Upvotes: 1

Views: 359

Answers (2)

anubhava
anubhava

Reputation: 784958

You may use this regex:

/^(?! )(?!.* $)[\w *()\[\]'"\/.&–-]+$/gm

RegEx Demo

Details:

  • ^: Start
  • (?! ): Negative lookahead to assert that we don't have a space at start
  • (?!.* $): Negative lookahead to assert that we don't have a space at end
  • [\w *()\[\]'"\/.&-]+: Match 1+ of the allowed characters
  • $: End

Note that \w is same as [a-zA-Z0-9_]

Upvotes: 0

Stefan Gabos
Stefan Gabos

Reputation: 1471

^[^\s][\w\s\(\)\[\]\'\"\/\.\-\&\–]+[^\s]$
  • ^ - start
  • [^\s] - no white space
  • [\w\s\(\)\[\]\'\"\/\.\-\&\–]+ - at least one of those characters (\w means [a-zA-Z0-9_])
  • [^\s] - no white space
  • $ - end

Upvotes: 2

Related Questions