Custom validators

I've got a slight issue implementing a custom validator from the example in the guide. Basically, I'm not sure where to get the error message from when validation fails. The example shows a field 'ErrorMessage' which doesn't exist.

I could of course just hard-code the error message, but it looks like there is a way to define error messages in the attribute instance. Anyway, this is the example I am referring to:

function TMyDataValidator.Validate(const Value: TValue;
  Context: IValidationContext): IValidationResult;
begin
  // Add your own logic to check if Value is valid
  if IsValid(Value) then
    Result := TValidationResult.Success
  else
    Result := TValidationResult.Failed(Format(ErrorMessage,
      [Context.DisplayName]))
end;

Any suggestions?

1 Like

The ErrorMessage in the example is just up to you. Yes, you should replace it with a hard-coded message, or, if you want it to be customizable from the attribute, you can simply set it when creating the validator.

For instance, consider the Required attribute. This is how it's implemented:

constructor RequiredAttribute.Create(const ErrorMessage: string = ''; const ErrorCode: string = '');
begin
  inherited Create;
  FValidator := TRequiredValidator.Create(ErrorMessage, ErrorCode);
end;

function RequiredAttribute.GetValidator: IValidator;
begin
  Result := FValidator;
end;

You see that ErrorMessage is one of the attribute parameters. It's passed to the TRequiredValidator class. You can do the same with your TMyDataValidator, and use it for your error message.

Ah okay, I thought it could somehow tap into an 'automatic' error message. That's great, I know what to do now. Thx

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.