valitron icon indicating copy to clipboard operation
valitron copied to clipboard

Add custom message in custom rule

Open lucaromano-intelligentia opened this issue 1 year ago • 0 comments

I suggest the possibility of inserting the error message as the return value of the custom rule, in addition to the validation status.

In the following case, I add the rule that checks whether a json is valid according to a pattern.

\Valitron\Validator::addRule('json_schema', function ($field, $value, array $params, array $fields) {
	if (!json_validate($value) || !count($params)) {
		return false;
	} else {
		// schema not available
		if (curl_init($params[0]) === false) {
			return false;
		} else {
			$schema = Schema::import($params[0]);
			try {
				$properties = json_decode($value);
				$schema->in($properties);
				$is_valid = true;
			} catch (\Throwable $exception) {
				$is_valid = false;
			}
			return $is_valid;
		}
	}
}, '{field} does not match the schema');

It would be useful if the message passed was a default message, but if a new message is provided within the function, it is overwritten, as in the following example, which message is returned together with the validation status.

\Valitron\Validator::addRule('json_schema', function ($field, $value, array $params, array $fields) {
	if (!json_validate($value) || !count($params)) {
		return false;
	} else {
		// schema not available
		if (curl_init($params[0]) === false) {
			return [false, "The schema is not available"];
		} else {
			$schema = Schema::import($params[0]);
			$is_valid = null;
			try {
				$properties = json_decode($value);
				$schema->in($properties);
				$is_valid = true;
			} catch (\Throwable $exception) {
				$message = $exception->getMessage();
			}
			return ($is_valid) ?? return [false, $message];
		}
	}
}, '{field} does not match the schema');