Luca Sepe Luca Sepe - 1 month ago 9
jQuery Question

Make a form date value optional

In my aplication, the query results are showed using jquery Data Table.
The last task is add a date field to form search, but this value is optional for final user (as the others of form).

This is the code section where I initialize the fields with the form data:

DTevents = $('#eventsdata').DataTable(
{
"serverSide": true,
"ajax":{
url: "../getevents.json",
type: "post",
"data": function (d)
{
return $.extend(d, {typename : $('#typename').val()}, {infoname : $('#infoname').val()},
{hostname : $('#hostname').val()}, {datevalue : moment($('#datevalue').val()).toDate().getTime() });
}

},


The other fields are also accepted if empty; for this, in my Spring controller, I used this code:

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}


As you can see, the date is given in input to moment.js to convert into long to pass to Controller. If I query the app without insert a value for other fields, it works perfectly (a query without value from Form is used to perform a
SELECT *
in our scenario).

But now, if I left the date empty, I obtain an empty table and a console message:

2017-08-23 12:32:44.870 WARN 8396 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: "NaN"


So my question is: how can I tell to my app that also the "date" field is optional?

Answer Source

Spring controller throw the exception because he expects value of type long, but you pass the parameter always, also if the value of datevalue is blank. In this case moment function getTimestamp will return NaN (not a number) as String and the controller complaines because of the wrong type. Try to avoid send the parameter if the user doesn't insert it:

{
    var param = {typename : $('#typename').val(), infoname :  $('#infoname').val(), hostname :  $('#hostname').val() };

    if(moment($('#datevalue').val()).isValid()){
        param = $.extend(param, {datevalue : moment($('#datevalue').val()).toDate().getTime()});
    }

    return $.extend(d, param);

}

Pay attention to the isValid method if you don't use standard iso date format you have to tell moment which format you use. Example if you use dd/MM/yyyy format:

moment('23/08/2017', "DD/MM/YYYY", true).isValid()