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:
- Length can be “auto”
- Has a floating point number with an optional + or – sign.
- 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.
- 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)?$

Leave a reply to Shamasis Bhattacharya Cancel reply