Search code examples
javaspringjakarta-eebean-validationspring-validator

Setting Custom Field Name and Code


I am trying to use Bean Validation for validation in my Spring App. I have the below field defined in my bean -

@NotNull(message = "CUSTOMERROR-1000")
private String firstName;

Here I have defined CUSTOMERROR-1000 as "Field is mandatory" in my property file. In my ControllerAdvice class , i am able to retrieve the details using the code below :

getBindingResult().getFieldError().getField()
getBindingResult().getFieldError().getCode()
getBindingResult().getFieldError().getDefaultMessage()

Here I get the field name as firstName. Is there a way to annotate the field and set the value as "First Name"? Similarly is there a way to set the code value via annotation?


Solution

  • For that, you need to create your own constraints. Than you can add additional properties, label, errorCode etc., set values to them and use them. See: http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-compound

    Than you can define your error message like this: Error code: {errorCode} - {label} is mandatory