JSON Validation

Examples for validating JSON objects.

by Pat Cullen

HTML

<script src="http://b22222.com/files/JSONValidate.js"></script>
<textarea id="input">{
    name: 'Toys',
    ownerEmail: 'mac@cheesy.',
    contents: [
        {
            code: 'sk', name: 'Skateboard',
            price: 99.98,
            isNew: false, isOld: false
        },
        {
            code: 'lg', name: 'Lego Mindstorms',
            price: 299,
            isNew: false, isOld: true
        },
        {
            code: 'helicopter', name: 'Radio Controlled Helicopter',
            price: 149,
            isNew: true, isOld: true
        }
    ]
}
</textarea>
<button type="button" id="check">Validate</button>
<div id="result"></div>

CSS

#input {
    width: 99%;
    height: 320px;
    font: 12px Monospace;
}
#check {
    display: block;
    margin: 10px;
    font-size: 16px;
}
#result {
    color: green;
}
#result.err {
    color: red;
}

JavaScript

jv.regex = {
    alphaNumeric: /^[a-z0-9\.]+$/i,
    email: /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/
};

jv.schema = {};

jv.schema.product = {
	name:   { type: 'string', min: 3, max: 120 },
    code:   { type: 'string', min: 1, max: 4, regex: jv.regex.alphaNumeric },
	price:  { type: 'number', min: 0 },
	isNew:  { type: 'boolean', label: 'New Stock' },
	isOld:  { type: 'boolean', label: 'Old Stock',
        // check that items are not 'New' and 'Old' at the same time
        custom: function(v, o) {
		    if (v && o.isNew) return ['Products cannot be \'new\' and \'old\'.'];
	    } 
    }
};

jv.schema.box = {
	name:     { type: 'string', min: 1, max: 120 },
    ownerEmail: { type: 'string', null: true, regex: jv.regex.email },
    contents: { type: 'object', array: true, schema: jv.schema.product, 
        // at least one object must be 'new', and at least one 'old'
		custom: function(v) {
            var hasNew, hasOld;
			for (i = v.length-1; i >= 0; i--)
				if (v[i].isNew) hasNew = true; else
                    if (v[i].isOld) hasOld = true;
            if (!hasNew || !hasOld) 
                return ['Must have at least one \'new\' and at least one \'old\' product.'];
		}
	}
};

// on window ready, setup the stage
window.addEvent('domready', function() {
    $('check').addEvent('click', function() {
        // get the value from the textbox, and try decode into JS object
        var test = JSON.decode($('input').get('value'));
        if (test == null) {
            $('result').addClass('err').set('text', 'JSON Syntax error');
        } else {
            // *** Validate the object against the above schema
            result = jv.validate(test, jv.schema.box);
            // and display results accordingly
            if (result.st == 'er')
                $('result').addClass('err').set('text', result.msg[0]);
            else
                $('result').removeClass('err').set('text', 'Yay! The JSON validated.');
       ...