Regular Expression To Validate CSS Length and Position Values

In CSS, length and position of various elements are provided as decimal numbers. Width, height, margin, padding, border-thickness, etc are some example CSS attributes where we need to specify a length.

A valid CSS length value follows a set rule:

  1. Length can be “auto”
  2. Has a floating point number with an optional + or – sign.
  3. The floating point number has a trailing length unit (The valid CSS length units are: absolute (in, cm, mm, pt, pc) units and relative (em, ex, px) units. For more information on CSS length units, see MSDN Library: http://msdn.microsoft.com/en-us/library/ms531211(VS.85).aspx) or percentage.
  4. Percentage cannot be negative.

The above can be validated using Regular Expressions in very simple steps.

A comprehensive RegEx to validate the CSS length value would be:
^auto$|^[+-]?[0-9]+\\.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)?$

Explanation of the above expression:

^auto$ indicates that the string can be exactly “auto”

^[+-]? allows for the value to optionally begin with a plus or minus sign. A caret ^ sign before any regular expression specifies that the expression should match the beginning of a string.

[0-9]+\.?([0-9]+)? represents a floating point number with optional decimal. A question mark after any literal marks that expression as optional. Here \.? denotes an optional decimal point and even the figures proceeding this is optional.

(px|em|ex|%|in|cn|mm|pt|pc)?$ signifies that the value can optionally end with either of the nine possible units. A $ at the end of an expression indicates that the expression should match the end of the string.

Note: To effectively use this Regular Expression on a single string or single value, use the i and g modifiers to make the parsing case insensitive and global.

Other variants of the CSS length validator Regular Expression:

A RegEx without considering point 1 (auto) will simply be:
^[+-]?[0-9]+\.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)$

Another example of the RegEx with point a and point 3 as optional:
^[+-]?[0-9]+\.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc)?$

2 responses

  1. I think the spec says .5px is valid but not 5.px like your regexp looks to me. Also, 0 with no units is valid.

    Like

    1. The section of the regex 0-9]+.?([0-9]+)? has a question-mark at the end of it, indicating that post decimal point number is optional. Thus “5.px” is valid!

      Also 0 and any other unit-less number is marked as valid by this regex. I prefer this because many older CSS implementations have unit-less values where default unit is browser specific.

      Like

Leave a reply to Shamasis Bhattacharya Cancel reply