Skip to content

Commit a6b9149

Browse files
committed
Directive to add integer and float parsing
1 parent 865f55e commit a6b9149

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/default.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
ng-class="form.fieldHtmlClass"
3030
ng-disabled="form.readonly"
3131
name="{{form.key.slice(-1)[0]}}"
32+
sf-type-parser="form.schema"
3233
schema-validate="form">
3334
<div ng-messages="ngModel.$error">
3435
<!--

src/type-parser.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* It might be a bug, but currently input[type=number] does not add
3+
* a parser, so the model gets populated with a string. It does however stop non numbers so it
4+
* must have some preproccessing. Anyway, this adds parser before schema-validate hooks into it.
5+
* FIXME: this is still not a complete solution. Inputting a string in an input[type=number] results
6+
* in parsers never firing and ngModel value removed. So no validation from schema-validate either.
7+
*/
8+
angular.module('schemaForm').directive('sfTypeParser', function() {
9+
return {
10+
restrict: 'A',
11+
scope: false,
12+
require: 'ngModel',
13+
link: function(scope, element, attrs, ngModel) {
14+
var once = scope.$watch(attrs.sfTypeParser, function(schema) {
15+
if (!schema) {
16+
return;
17+
}
18+
19+
var isNumber = schema.type.indexOf('number') !== -1;
20+
var isInteger = schema.type.indexOf('integer') !== -1;
21+
var numberRE = /^[0-9]*$/;
22+
// Use index of since type can be either an array with two values or a string.
23+
if (isNumber || isInteger) {
24+
// The timing here seems to work. i.e. we get in before schema-validate
25+
ngModel.$parsers.push(function(viewValue) {
26+
var value;
27+
if (isNumber) {
28+
value = parseFloat(viewValue);
29+
} else if (numberRE.test(viewValue)) {
30+
// We test the value to check that it's a valid integer, otherwise we can easily
31+
// get float -> integer parsing behind the scenes.
32+
value = parseInt(viewValue, 10);
33+
}
34+
console.log('parser', numberRE.test(viewValue), viewValue, value)
35+
if (value === undefined || isNaN(value)) {
36+
//Let the validation fail. @FIXME: it fails with "required" for some reason.
37+
return viewValue;
38+
}
39+
return value;
40+
});
41+
}
42+
43+
once();
44+
});
45+
}
46+
};
47+
});

0 commit comments

Comments
 (0)