sanjay
sanjay

Reputation: 61

Regex for validating fields

I am using validation engine to validate fields with regex. I am almost done with my work but have a problem. I am unable to make a regex for:

  1. Leading and trailing spaces are not allowed.
  2. Multiple spaces in between are not allowed (Single space is allowed).

I want regex only for these conditions so that i can put this on any field.

Upvotes: 0

Views: 194

Answers (3)

Bennor McCarthy
Bennor McCarthy

Reputation: 11675

Insisting someone enters data without leading or trailing spaces when every language has access to some sort of trimming function is pretty lazy (and really bad usability). Likewise with double spaces: Just replace " " with " ".

If you really must do it with regex, this should work:

/^\S+(?!.*\s\s).*\S$/

This does make the assumption that a valid string has at least two characters (the \S at the start, and the \S at the end). If you want to allow a single character string, this will work:

/^(?!\s.*)(?!.*\s\s).*\S$/

Alternatively, if you are trying to do the inverse and match the invalid input, this will work (i.e. any matches for this regex mean the string isn't valid):

/^\s|\s\s|\s$/

Unless there's a good reason you can't, the last option is probably best even for matching valid input. i.e. something like this:

var isValid = !value.match(/^\s|\s\s|\s$/); // instead of "var isInvalid = value.match(/^\s|\s\s|\s$/);"

The reason this is preferable is that it's a lot easier for someone to understand, and you should always favour readability in your code.

Upvotes: 2

powtac
powtac

Reputation: 41040

var s = "test test  test ";

// Find multiple spaces
if(s.indexOf("  ") !== -1) {
    alert('Multiple spaces found');
}

// Find leading or trailing space
if (s.indexOf(" ", 0) === 0 || s.indexOf(" ", s.length-1) != -1) {
    alert("Leading or trailing space found");
}

See this Fiddle example http://jsfiddle.net/powtac/b5mHr/2/

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336088

/^(?!\s)(?!.*\s{2})(?!.*\s$)/

should do this, unless your input may contain newlines. If that is the case, use [\s\S] instead of ..

Explanation:

^           # Start of string
(?!\s)      # Assert that the first character isn't whitespace
(?!.*\s{2}) # Assert that there are no two consecutive whitespace characters
(?!.*\s$)   # Assert that the last character isn't whitespace

Upvotes: 0

Related Questions