Hi there, I need some help from experts with custom validation. In my case the validation message has a dynamic value. Little background, I have a number field with decimal value. End user can customize it to set whatever precision they want for the decimal. I am planning to use RegEx to validate the value and I must use a directive. Problem is, after I set the ExternalValidation, its shows the custom message but then it gets replaced with "Please add error message for null". How do I make the original message stick? Or, is there another way to achieve this?
Below is my code for your reference.
.directive('cfNumber', ['validationManager', '$window',function(validationManager, $window) {
return {
restrict: 'A',
require: 'ngModel',
priority: 100,
link: function($scope, iEl, iAttrs, ctrl) {
$scope.precision = 4;//$scope.input.options.precision;
var regex = /^\d+(()|(\.\d{1,4})?)$/;
var validator = function(value){
if(value.toString().length > 0 && (parseFloat(value) === 'NaN' || !regex.test(parseFloat(value)))){
ctrl.$valid = false;
ctrl.$setValidity(null,false);
ctrl.setExternalValidation(null,"Number must have " + $scope.precision + " decimal places.",false);
//validationManager.setElementValidationError(iEl, null, "Number must have " + $scope.precision + " decimal places.");
}
return $window.parseFloat(value) ? ''+value : value;
};
ctrl.$parsers.push(validator);
ctrl.$formatters.push(validator);
}
}
}])
Another option is to set the error message like following:
defaultErrorMessageResolver.getErrorMessages().then(function(errorMessages) {
errorMessages['decimalValidation'] = 'Number must have {0} decimal places.';
});
With below directive, however, I'm not sure how to replace {0} with that value that comes in from the input field <input ng-model="numberField" validate-decimal="4" type="number">
.directive('validateDecimal', ['validationManager', '$window',function(validationManager, $window) {
return {
restrict: 'A',
require: 'ngModel',
priority: 100,
link: function($scope, iEl, iAttrs, ctrl) {
$scope.precision = 4;//$scope.input.options.precision;
var regex = /^\d+(()|(.\d{1,4})?)$/;
var validator = function(value){
if(value.toString().length > 0 && (parseFloat(value) === 'NaN' || !regex.test(parseFloat(value)))){
ctrl.$setValidity('decimalValidation',false);
}
else {
ctrl.$setValidity('decimalValidation',true);
}
return $window.parseFloat(value) ? ''+value : value;
};
ctrl.$parsers.push(validator);
ctrl.$formatters.push(validator);
}
}
}])