marioosh
marioosh

Reputation: 28566

Spring MVC: simple validation without @ModelAttribute / "command object"

How to validate a simple form (one input field) and show errors without providing a command object ? My simple form is:

    <form id="verify" action="check.html">
        <input name="code"/>
        <form:errors path="code" />         
        <input type="submit" value="ok" />      
    </form>

Controller handler method below. I need to generate error message and show in place of form:errors

@RequestMapping("/check.html")
public String check(@RequestParam(value="code") String code) {
    if(!isGood(code)) {
        // How to bind some error messages for `code` ?
        return "fail"; // fail page
    }
    return "ok";
}

Upvotes: 3

Views: 3282

Answers (1)

axtavt
axtavt

Reputation: 242686

In short words, <form:errors> doesn't work without <form:form> and other @ModelAttribute-related functionality. If you want the simpliest solution, you can export error message as a normal model attribute instead of using <form:errors>:

@RequestMapping("/check.html")
public String check(@RequestParam(value="code") String code, ModelMap model) {
    if(!isGood(code)) {
        model.put("codeError", "...")
        return "fail"; // fail page
    }
    return "ok";
}

    <form id="verify" action="check.html">
        <input name="code"/>
        <c:out value = "${codeError}" />            
        <input type="submit" value="ok" />      
    </form>

Upvotes: 6

Related Questions