How to check date format in spring form

I'm new to Spring, and I'm trying to create a form that checks the date format (that is: it only accepts dates with the format " MM/dd/yyyy", if the user puts " mm-dd-yyyy", it should show an error message).

How can I achieve this with Spring?

I read a lot of messages and answers, such as this and which are recommended for use @InitBinderin the controller (I tried, but could not get it to work by the way). But what if I have a form with different dates? or if my controller manages multiple send requests from different forms, and each of them requires checking for different dates?

I currently have this form:

<form:form action="getReportFile.html" commandName="staticReportForm">
            <table>
                <tr>
                    <td>Reports:</td>
                </tr>
                <tr>
                    <td><form:select path="report" items="${staticReports}"/>                        
                    </td>
                </tr>
               <tr>
                   <td>Date (MM/DD/YYYY) (empty for most recent possible):<FONT color="red"><form:errors
                                path="date" /></FONT></td>
               </tr>
               <tr>
                   <td><form:input path="date" /></td>
               </tr>
               <tr>
                   <td><input type="submit" value="Submit" /></td>
               </tr>
           </table>            
       </form:form>

bean, ( @DateTimeFormat , ):

public class StaticReportForm {
        @NotEmpty        
        private String report;    
        @DateTimeFormat(pattern="MM/dd/yyyy")
        private Date date;

    public String getReport() {
        return report;
    }

    public void setReport(String report) {
        this.report = report;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }


}
+5
1

, spring, , , - jQuery DatePicker InitBinder.

JS :

<form:input cssClass="datepicker" path="someProperty" readonly="true" />

JS:

$(document).ready(function() {
    $('.datepicker').datepicker();
});

:

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    sdf.setLenient(true);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}

Mismatch , , . , jQuery DatePicker, ( , MM/dd/yyyy). , , Spring CustomEditor String . , BindingResults ( ). , , Mismatch.

: , ...

Bean -, ( View to Controller). , .

public class SomeBean {
    private Date someDate;
    // ...additional properties, getters, setters...
    public Date getSomeDate() { return someDate; }
    public void setSomeDate(Date date) { somedate = date; }
}

. Model

@SessionAttribute.
@Controller
@RequestMapping("/somePath")
@SessionAttributes({"someFormBean"})
public class SomeController {
    /**
     * Handler method
     */
    @RequestMapping()
    public String defaultView(@ModelAttribute("someFormBean") SomeBean someFormBean, Model uiModel) {
        // Do something in your default view
        return "someDefaultView";   // Assuming you have a ViewResolver, like JspViewResolver or Tiles
    }

    /**
     * Submission Handler method
     */
    @RequestMapping(method = RequestMethod.POST
    public String submit(
        @ModelAttribute("someFormBean") SomeBean someFormBean, 
        BindingResult bindingResults,
        Model uiModel) {
        // bindingResults will have your errors from binding
        if(bindingResults.hasErrors()) {
            return "errorView";
        } else {
            return "successView";
        }
    }

    /**
     * Will be called to create your Model Attribute when its missing
     */
    @ModelAttribute("someFormBean")
    public SomeBean createSomeBean() {
        return new SomeBean();
    }

    /**
     * register property editors
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
        // You can register other Custom Editors with the WebDataBinder, like CustomNumberEditor for Integers and Longs, or StringTrimmerEditor for Strings
    }   
}

( "someDefaultView" , JSP , Spring JSTL)

<%@ taglib prefix="c"       uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt"     uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn"      uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="form"    uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring"  uri="http://www.springframework.org/tags" %>
<html>
    <head>
        <script type="text/javascript" src="/resources/jquery/1.7.1/jquery-1.7.1.min.js"></script>
        <script type="text/javascript" src="resources/jquery.ui/1.8.13/jquery.ui.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                $('.datepicker').datepicker();
            };
        </script>
    </head>
    <body>
        <form:form modelAttribute="someFormBean">
            <form:input cssClass="datepicker" path="someDate" readonly="true" /><br />
            <form:errors path="a"/><br /><br />
            <input type="submit" value="Submit" />
        </form:form>
    </body>
</html>

, Google'ing Spring Init Binders, cusomizing binding errors (typeMismatch) JSR 303 , . , , , , , , . , , , 20 , . , .

+7

All Articles