Skip to content

Added support for custom messages when creating/throwing a DF_REST_ValidationFailure

Purpose

When writing code that does 'custom' validation, e.g. checking that a client has sufficient credit to purchase an artwork of a certain value, I have been throwing DF_REST_Exceptions. However this is not really an exceptional circumstance: it's a reasonably foreseeable outcome that is more in line with validation.

This change allows custom validation code to throw DF_REST_ValidationFailures with custom messages — prior to this the process would only report errors that were actually picked up by form validation with DF_Form_validation.

What I did

  • Added support for supplying single or multiple custom messages when creating/throwing a new DF_REST_ValidationFailure.
  • Updated handle_api_method_exception() in DF_REST_Controller to merge those messages into its output, if they are present.

Implications

  • I have removed the optional $return argument when creating a DF_REST_ValidationFailure. This is technically a breaking change, but I very much doubt anyone has ever used it, or the following arg.

I initially put in some argument-shuffling code for compatibility, but then realised that the $return argument didn't really make sense in this context — I think I had put it in there to optionally pass through to get_errors_json() in DF_Form_validation, but can't see any use for that.

  • I have only updated the AJAX path in handle_api_method_exception().

Setup

None

How to test

  • Code review
  • In any API endpoint based on DF_REST_Controller, throw a new DF_REST_ValidationFailure() with string and array arguments.
    • Observe that if you use a form field name as a key, it will place the message against that field as expected.
  • Alter a set of validation rules to cause a back-end form_validation failure.
  • Use code like this to run the validation:
if (! $this->form_validation->set_rules($config)->run())
{
	throw new DF_REST_ValidationFailure();
};
  • Confirm that this still works as expected.
  • Add a custom message or messages into the throw, and confirm that both the 'real' form validation error appears and also the custom one.

Merge request reports