Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom message in custom rule #379

Open
lucaromano-intelligentia opened this issue Jul 19, 2024 · 0 comments
Open

Add custom message in custom rule #379

lucaromano-intelligentia opened this issue Jul 19, 2024 · 0 comments

Comments

@lucaromano-intelligentia

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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant