I have a basic JSON API written in PHP. I want to validate incoming JSON data.
I know there are PHP JSON validators out there, here is a quick one I just rolled up.
<?php
$json_payload = json_decode('{
"data": {
"a_string": "short",
"a_number": 7
}
}');
validateJSONPayload(
'{
"data": {
"a_string": "type=string,min_length=7,max_length=10",
"a_number": "type=integer,min=8,max=50"
}
}',
$json_payload
);
function validateJSONPayload($json_schema, $json_payload){
$json_schema = json_decode($json_schema);
function reCursiveCheck($schema_value, $schema_type, $payload_value, $payload_type){
if($schema_type === "object" || $schema_type === "array"){
# KEEP LOOPING
foreach ($schema_value as $key => $key_val) {
if(!property_exists($payload_value, $key)) echo "validation failed because the data does not match the schema<br />";
reCursiveCheck($key_val, gettype($key_val), $payload_value->{$key}, gettype($payload_value->{$key}));
}
} else {
# VALUE IS A STRING, NUMBER, BOOL, NULL
$validation_param_strings = explode(",", $schema_value);
# STORE THE PARAMS TO CALL THE VALIDATION FUNCTION
$validation_params = array();
foreach($validation_param_strings as $validation_param) {
$params = explode("=", $validation_param);
$validation_params[$params[0]] = $params[1];
}
// print_r($validation_params);
validateProperty($payload_value, $payload_type, $validation_params);
}
}
function validateProperty($payload_value, $payload_type, $validation_rule){
if($payload_type !== $validation_rule["type"]) {
echo "types do not match<br />";
}
# STRING VALIDATION
if($validation_rule["type"] === "string"){
if(strlen($payload_value) > $validation_rule["max_length"]) echo "string too long<br />";
if(strlen($payload_value) < $validation_rule["min_length"]) echo "string too short<br />";
}
# NUMBER VALIDATION
if($validation_rule["type"] === "integer"){
if($payload_value > (int)$validation_rule["max"]) echo "number too large<br />";
if($payload_value < (int)$validation_rule["min"]) echo "number too small<br />";
}
# NULL VALIDATION
if($validation_rule["type"] === "null"){
echo "found a null<br />";
}
}
foreach($json_schema as $key => $value) {
if(!property_exists($json_payload, $key)) echo "validation failed because the data does not match the schema<br />";
reCursiveCheck($value, gettype($value), $json_payload->{$key}, gettype($json_payload->{$key}));
}
}
?>