Validation•9 min read
CSS and JavaScript Validation: Code Quality Guide
Validate CSS and JavaScript code for errors and best practices. Learn syntax validation, linting, and common issues.
By Andy Pham
CSS and JavaScript Validation: Code Quality Guide
Validating CSS and JavaScript catches errors early, improves code quality, and ensures cross-browser compatibility.
CSS Validation
Common CSS Errors
- Syntax Errors
/* Missing semicolon */
.box {
color: red
background: blue;
}
/* Invalid property */
.box {
colours: red;
}
/* Missing closing brace */
.box {
color: red;
- Browser Compatibility
/* Needs vendor prefixes */
.box {
display: flex;
/* Should include: -webkit-flex, -ms-flexbox */
}
- Specificity Issues
/* Overly specific selector */
body div.container ul li a.link { }
/* Better */
.nav-link { }
CSS Validation Tools
// Using stylelint
const stylelint = require('stylelint');
const result = await stylelint.lint({
code: cssString,
config: {
rules: {
'color-no-invalid-hex': true,
'property-no-unknown': true
}
}
});
JavaScript Validation
Common JavaScript Errors
- Syntax Errors
// Missing closing bracket
function hello() {
console.log('Hello'
// Unexpected token
const x = ;
// Invalid assignment
const 123abc = 'test';
- Runtime Issues
// Undefined variable
console.log(undefinedVar);
// Type error
null.toString();
// Reference before declaration
console.log(x);
let x = 1;
JavaScript Validation Tools
// Using Esprima for syntax check
const esprima = require('esprima');
try {
esprima.parseScript(code);
console.log('Valid JavaScript');
} catch (error) {
console.log('Error:', error.message);
}
// Using ESLint
const { ESLint } = require('eslint');
const eslint = new ESLint();
const results = await eslint.lintText(code);
Validation Best Practices
CSS
- Use a CSS preprocessor (Sass, Less)
- Implement autoprefixer
- Follow a naming convention (BEM, etc.)
- Validate during build
JavaScript
- Use TypeScript or JSDoc
- Configure ESLint rules
- Enable strict mode
- Write unit tests
IDE Integration
VS Code
// settings.json
{
"css.validate": true,
"javascript.validate.enable": true,
"eslint.enable": true,
"stylelint.enable": true
}
Try Our Validators
- CSS Validator - Validate CSS syntax
- JavaScript Validator - Check JS code
- JSON Validator - Validate JSON
Conclusion
Regular validation catches errors early and maintains code quality. Integrate validation into your development workflow.