9

Is there a library out there which will validate CSS?

The only tools I can find to do so are web sites. If one of these sites has an API, that would fit the bill, too.

I have a script that serves as a CSS compiler. It sets various variables according to settings for a theme, and generates and writes a CSS file. Before committing to writing the CSS file, I'd like to validate it to make sure there aren't any invalid entries.

PHP would be convenient, but Python, Perl, Ruby, Java, or anything executable from a shell would be fine.

Ideally, there's something out there that I can use as part of a sequence like:

 $css_file=theme_compile('theme-name');
 if(!validate_css($css_file)){
   echo "css file contained invalid entry 'width:px'";//just an example, of course
   }   
 else{
   file_put_contents('/path/css_file',$css_file);
   }

3 Answers 3

10

W3C has an API:

http://jigsaw.w3.org/css-validator/api.html

You can also download the validator and run it locally: http://jigsaw.w3.org/css-validator/DOWNLOAD.html

You need to be able to run java from your script.

4
  • 3
    It is a good idea to download the validator and run it locally if you are going to hit it a lot though. You'll get better performance and you won't be eating up the service's bandwidth.
    – Quentin
    Jul 25, 2010 at 19:02
  • @David Yup. But I'd imagine in the OP's case he won't be running it a lot Jul 25, 2010 at 19:03
  • 1
    He's doing it often enough to automate the process.
    – Quentin
    Jul 25, 2010 at 19:13
  • Thanks! That's the canonical source, I guess. I do run this several times a day during development, so their Java program is ideal.
    – JAL
    Jul 25, 2010 at 23:13
3

Python library:

http://cthedot.de/cssutils/

3

There is a pear package called Services_W3C_CSSValidator which does this. You can download the PHP class directly from the github if you prefer.

Its very simple to use.

require_once 'Services/W3C/CSSValidator.php';
$v = new Services_W3C_CSSValidator();
$result = $v->validateFile('pear_manual.css'); // XML

It includes all features available at http://jigsaw.w3.org/css-validator

Not the answer you're looking for? Browse other questions tagged or ask your own question.