Only a few weeks ago we were discussing the seemingly undocumented and unsupported extension type called customValidation. Whilst reading the documentation online, we can across a couple of other validation-related items that could prove to be extremely useful. We’re not clear when they arrived in the product but in any case, let us have a look at control.setError() and control.validateTextInput(). These are two methods of the control object that deal with validation and errors.
control.setError("Some Message")
The control.setError() method, as it’s name suggests, allows you to “throw an error” for a control. The error message is displayed using the standard error message (unless you have restyled that) block underneath the control:

That is interesting, in and of itself. It allows the developer to override the Error Message set at the attribute level:

The method really comes into it’s own when you associate it with the second method, control.validateTextInput()
var myValidation = control.validateTextInput(control.getValue());
The variable above will either be null (which means the validation succeeded and not error was encountered) or it will be an object with two properties, cause and message. The cause will either be “validation” or “mandatory”. So for the first time ever, we can easily distinguish between the two types of error for the control, and react differently in each case.
The message property contains either “this value is mandatory” (or a localised or custom string you added to the Styles dialog) or the message defined in the attribute. With the above example, if both errors occurred you would see this as output.

With these two methods we can now build a validation key for our customInput which shares custom messages (for example with dynamic content such as hint text) for each scenario:
The code can switch between the two causes and provide different feedback.
switch (myValidation.cause) {
case "mandatory":
control.setError( control.getHintText() + " is required.");
break;
case "validation":
control.setError(control.getHintText() + " failed validation.");
break;
default:
control.setError("Unexpected Error Message");
break;
}
The end result in the browser looks like this:

You can find the Zip Archive in the online store.