3

What are some guidelines that could be used on CSS to ensure that it is valid at least in syntax only. The four checks that I came up with were ensuring that at least one "{", "}", ";" and ":" exist and if they do exist that the number of "{" and "}" matches and the number of ":" and ";" match. I also check to make sure it starts with a "." and ends with ";}" with all possible combinations of whitespace.

Are there any other checks I could run on it just to make sure it is valid syntax?

Or better yet does anyone have a regex available that could verify this? I'm extremely new to regex but it seems like it would be able to handle all the checks I've mentioned.

5
  • Why not just use jigsaw.w3.org/css-validator ? Commented Sep 27, 2011 at 13:23
  • +1 for a kind of interesting heuristic problem Commented Sep 27, 2011 at 13:24
  • 1
    Why are you trying to do this? Commented Sep 27, 2011 at 13:26
  • I guess the main thing that would trip you up is strings. Comments are relatively easy to strip out, but strings kind of force you into doing some kind of little state machine. Commented Sep 27, 2011 at 13:28
  • 1
    I have a site that my boss wants the user to be able to customize and adding in CSS was one of the ways they asked about. Verifing the syntax upon entry just seemed like a good idea. I've placed a warning on the page to try to scare the average user away from trying to use CSS and also let them know not to include comments in the CSS they submit. Commented Sep 27, 2011 at 14:13

2 Answers 2

4

The simplest suitable regex that I can think of is:

(([.#]?[a-zA-Z_-0-9]+\ *)+\{([a-zA-Z-])+\ *\:[^;]+;\})+

It doesn't consider @charset ...; directives and comments (\* ... *\), also it doesn't check for braces in url(...) and "..." pairs in content: "...", but you can try adding this by yourself if you need.

Sign up to request clarification or add additional context in comments.

4 Comments

What is the "-" portion of [a-zA-Z_-0-9] supposed to do? I was getting an error originally and it went away when I removed the "-." Once i took that out it worked perfectly for my needs. Not full validation as others have pointed out but incorporating a third party tool just for this didn't really strike me as worth the time.
The - is a character range indicator. Some regex engines can understand that in this case, _-0-9 means _, -, 0 to 9 but the engine you are using requires the - to be escaped when not used to express a character range.
Does it support !important etc?
fyi this declaration will fail: background-image: url(bad_unclosed_parens;
3

You can run it through the w3 css validator: http://jigsaw.w3.org/css-validator/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.