JSON Schema client side validator

Testing out client side JSON Schema validation provided by TV4 (https://github.com/geraintluff/tv4)

HTML

<script src="https://cdn.rawgit.com/geraintluff/tv4/master/tv4.js"></script>

JavaScript

/*

Author: James Cockshull

Testing out client side JSON Schema validation provided by TV4 (https://github.com/geraintluff/tv4)

External resource: https://raw.githubusercontent.com/geraintluff/tv4/master/tv4.js
which has been served through https://rawgit.com/ so that the correct content-type
headers are added.

*/


// The schema
var schema = {
    "id": "https://kitoutapi.lrsdedicated.com/v1/json_schemas/login-request#",
    "$schema": "http://json-schema.org/draft-04/schema#",
    "description": "Login request schema",
    "type": "object",
    "properties": {
        "email": {
            "type": "string"
        },
        "password": {
            "type": "string"
        },
        "nr": {
        	"type":integer
        }
    },
    "required": [
        "email",
        "password"
    ],
    "additionalProperties": false
};

 
// Test data 1
// This test should return a good result
var data1 = {
    "email":"[email protected]",
    "password":"password",
    "nr": 11
}


// Test data 2
// This test should return a bad result becuase
// an unexpected property 'foo' would be found
// when additionalProperties are not allowed. 
var data2 = {
    "email":"[email protected]",
    "password":"password",
    "foo":"bar"
}


// Test the data is valid against the schema's definition
var valid = tv4.validate(data1, schema);

// Print out the results...
console.log("Validity result: %s", valid);
console.log("Error object: %o", tv4.error);