I am writing a directive that will validate the Swedish social security number (personnummer). To be used on an input element like this:
<input type="text" ng-model="pnr" pnrvalidator />
The Swedish social security number is on the format yyyymmdd-nnnn
e.g 19121212-1212
My directive works as long as I use type="text"
. But since I would like that the number keyboard is used on mobile browsers,
then I changed to type="number"
:
<input type="number" ng-model="pnr" pnrvalidator />
Then my validator only works if I don't enter a dash (-) in my input e.g 191212121212 . If I enter 19121212-1212 then it's not a valid number. And the classes ng-invalid ng-invalid-number is added to my input element
When I wrote my directive I followed the documentation how to modifying built-in validators https://docs.angularjs.org/guide/forms
But it doesn't seem to apply to type=number
validation, or do I miss something?
I am using angular 1.3 (and 1.4).
My directive code:
angular.module('example').directive('pnrvalidator', function(){
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var validatePnr = function(inputString){
/*
* My validation logic here. Removed for this example
*/
};
ctrl.$validators.number = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
if (validatePnr(viewValue)) {
// it is valid
return true;
}
// it is invalid
return false;
};
}
};
});
A plunker with my example http://plnkr.co/edit/OFYG06YEFwKg8zrLYVN1?p=preview