gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

Support for HTML5 datetime, datetime-local etc #245

Closed blairbodnar closed 8 years ago

blairbodnar commented 8 years ago

Hi there,

How can I get my struct to render an HTML5 date, datetime, datetime-local etc for a date property?

For example:

//struct
export default t.struct({
    description: t.String,
    date: t.Date
});
//options
export default {
    fields: {
        date: {
            label: 'Date',
            type: 'datetime-local'
        }
    }
}

I've tried to set the type to 'date', 'datetime', etc, but it is always rendering as the 3 inputs. Is there any way to render it as an HTML5 datetime-local input?

gcanti commented 8 years ago

Hi, you should override the default factory and define a custom transformer:

const Type = t.struct({
  birtDate: t.Date
});

// a `date` input wants a yyyy-MM-dd format
function formatDate(v) {
  if (!v || t.String.is(v)) {
    return v;
  }
  let MM = (v.getMonth() + 1) + '';
  if (MM.length < 2) {
    MM = '0' + MM;
  }
  let dd = v.getDate() + '';
  if (dd.length < 2) {
    dd = '0' + dd;
  }
  return `${v.getFullYear()}-${MM}-${dd}`;
}

const options = {
  fields: {
    birtDate: {
      factory: t.form.Textbox,  // <= displays a textbox instead of the default component
      transformer: {            // <= required in order to handle the `date` input format
        format: formatDate,
        parse: (s) => s ? new Date(s) : null
      },
      type: 'date' // <= HTML5 attribute
    }
  }
};
blairbodnar commented 8 years ago

Ok great! Thanks! :)

gcanti commented 8 years ago

:+1: