Skip to content

Server Side Validation

James Cullum (Pseudonym) edited this page Dec 15, 2017 · 1 revision

json-forms helps you render and submit JSON data on the frontend. However, you still need to verify that the data submitted by the user matches your schema. While it is possible and for strict checking better to use proper JSON schema validators, this requires additional efforts in creating and managing the structure of the form in multiple places in parallel.

The code below is intended to provide useful helpers to compare the submitted data (created by bf.getData) with the schema of a JSON.


PHP

if(!compareStructure($_POST["json"], $schema)) die("Invalid JSON");

function compareStructure($data, $schema, $level = 0) {
	if(property_exists($schema, "type")) {
		if($schema->type == "object") {
			return compareStructure($data, $schema->properties, $level);
		} elseif($schema->type == "array") {
			return compareStructure($data, $schema->items, $level);
		}
	}
	foreach($data as $k=>$v) {
		if(!property_exists($schema, $k)) return false;
		if(is_object($v)) {
			if(!compareStructure($v, $schema->$k, $level+1)) return false;
		}
	}
	return true;
}
Clone this wiki locally