Form Validation – part 3 (more on Spring MessageSource concept)

In our previous example we have moved the validation message in property file studentmessages

Size.student1.studentHobby = Please enter a value for Student Hobby field between 5 and 25 characters.

But here we have some values hardcoded i.e [Student Hobby,min value 5 and max value 25]

In Spring this can be replace as

Size.student1.studentHobby = Please enter a value for {0} field between {2} and {1} characters.

Some points to remember here is:

Placeholder{0} is always replaced dynamically by Spring MVC with the name of field for which violation occurs.
For Example in our Demo Application,violaion occured for studentHobby field;so {0} was replaced with ‘studentHobby’

Placeholder{1},{2},{3},{4} and so on… would be replaced with the arguments values passed to the constraint annotation.
Example; we passed two arguments to Size annotation with min=5 and max=25,

so placeholders{1} and {2} were replaced with these arguments values.

You must be thinking why placeholders{1} will replace max argument value i.e 25 not with the min argument value i.e 5 and vice-versa.
The reason for this is Spring MVC uses alphabetical order of the arguments to decide upon which placeholder to be replaced with which argument value: in this demo,if we observe alphabetically -max comes before min argument so {1} would be replaced by max and {2} would be replaced by min value.


   

Comments are closed