Mehdi
Mehdi

Reputation: 3783

Spring MVC form validation

my problem is that I have a form which has html select element with some choosing option value & I want to validate those value using :

org.hibernate.validator.constraints
or
javax.validation.constraints

annotations. here is my select element:

<select name="status" id="tbSelect">
    <option value="ACTIVE">ACTIVE</option>
    <option value="LISTEN">LISTEN</option>
    <option value="DOWN">DOWN</option>
</select>

how I can for example validate the value of the options(DOWN,LISTEN,ACTIVE) inside the select element by using the annotation validators which I mention above?

my form is like this :

<form:form action="../agents/add" method="POST" commandName="myAgent">
     <form:select id="tbSelect" path="state">
            <form:option value="ACTIVE" path="state">ACTIVE</form:option>
            <form:option value="LISTEN" path="state">LISTEN</form:option>
            <form:option value="DOWN" path="state">DOWN</form:option>
    </form:select>

I have defined my controller method like this:

    @RequestMapping(value = "agents/add", method = RequestMethod.POST)
    public String addAgentSubmit(@ModelAttribute("myAgent") @Valid final AgentValidator agent, BindingResult result, RedirectAttributes redirect) {
      if (result.hasErrors()) {
        return "admin/agent/add";
      } 
       ...
    }

and I also define a ModelAttribute like this:

@ModelAttribute("myAgent")
 public AgentValidator getLoginForm() {
    return new AgentValidator();
 }

Here is my AgentValidator class also:

public class AgentValidator {
    @NotEmpty(message = "your state can not be empty !")
    private String state;

Upvotes: 2

Views: 5483

Answers (1)

n1ckolas
n1ckolas

Reputation: 4450

Since your state field looks more like an enumeration, first of all I would recommend to change state field into enum, let Spring MVC to bind that field and use only @NotNull annotation:

public class AgentValidator {
    @NotNull(message = "your state can not be empty !")
    private AgenState state;

Where AgentState is:

public enum AgentState {
    DOWN,LISTEN,ACTIVE
}

But if for certain reasons you can't change your model, then you may use custom constraints.

Particular you need to create your annotation AgentStateConstraint:

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = AgentStateConstraintValidator.class)
@Documented
public @interface AgentStateConstraint {

    String message() default "Some message";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

Then you need to create validator AgentStateConstraintValidator:

public class AgentStateConstraintValidator implements ConstraintValidator<AgentStateConstraint, String> {

    //Accepted values
    private static final Set<String> ACCEPTED_VALUES = new HashSet<String>(
            Arrays.asList(
                    "DOWN",
                    "LISTEN",
                    "ACTIVE"
            )
    );

    public void initialize(AgentStateConstraint constraintAnnotation) {
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        return ACCEPTED_VALUES.contains(object);
    }

}

Upvotes: 2

Related Questions