Permalink
Browse files

add widget.formatValue and implement custom formatValue for date fields

this puts the corrent value in the value attribute for date fields
  • Loading branch information...
1 parent aaeb266 commit 74abee99596056324b27d673135f7303c6e3634b @tellnes tellnes committed Mar 17, 2013
Showing with 47 additions and 3 deletions.
  1. +23 −2 lib/widgets.js
  2. +24 −1 test/test-widgets.js
View
@@ -64,14 +64,17 @@ var input = function (type) {
}
return attrs;
}, {});
+ w.formatValue = function (value) {
+ return value || null;
+ };
w.toHTML = function (name, f) {
if (!f) { f = {}; }
return singleTag('input', [{
type: type,
name: name,
id: f.id || true,
classes: w.classes,
- value: f.value || null
+ value: w.formatValue(f.value)
}, userAttrs]);
};
w.getDataRegExp = function () {
@@ -88,7 +91,25 @@ exports.text = input('text');
exports.password = input('password');
exports.hidden = input('hidden');
exports.color = input('color');
-exports.date = input('date');
+
+var dateWidget = input('date');
+exports.date = function (opt) {
+ var w = dateWidget(opt);
+ w.formatValue = function (value) {
+ if (!value) {
+ return null;
+ }
+
+ var date = value instanceof Date ? value : new Date(value);
+
+ if (isNaN(date.getTime())) {
+ return null;
+ }
+
+ return date.toISOString().slice(0, 10);
+ };
+ return w;
+};
exports.checkbox = function (opt) {
if (!opt) { opt = {}; }
View
@@ -18,6 +18,8 @@ var test_input = function (type) {
'<input type="' + type + '" name="field1" id="id_field1" value="some value" />'
);
test.equals(forms.widgets[type]().type, type);
+ test.equals(forms.widgets[type]().formatValue('hello'), 'hello');
+ test.strictEqual(forms.widgets[type]().formatValue(false), null);
test.done();
};
};
@@ -26,7 +28,28 @@ exports.text = test_input('text');
exports.password = test_input('password');
exports.hidden = test_input('hidden');
exports.color = test_input('color');
-exports.date = test_input('date');
+
+exports.date = function (test) {
+ var w = forms.widgets.date();
+ test.equals(w.formatValue(new Date(Date.UTC(2013, 2, 1))), '2013-03-01');
+ test.equals(w.formatValue('2013-03-02'), '2013-03-02');
+ test.strictEqual(w.formatValue('invalid'), null);
+
+ test.equals(w.type, 'date');
+
+ test.equals(
+ w.toHTML('field1'),
+ '<input type="date" name="field1" id="id_field1" />'
+ );
+
+ test.equals(
+ w.toHTML('field1', {value: '2013-03-03'}),
+ '<input type="date" name="field1" id="id_field1" value="2013-03-03" />'
+ );
+
+
+ test.done();
+};
exports.checkbox = function (test) {
test.equals(

0 comments on commit 74abee9

Please sign in to comment.