我有一个我创建的min和max指令,它检查输入是否在一个范围之间。我也有一个ng模式验证。我使用ng-messages显示我的验证。我有一个问题,即使用户已输入正确的模式,验证消息为"模式"仍在显示。我只想显示范围超出范围的验证。这是html
<form name="fee">
<input type="text" name="fee_classi" ng-model="main.fee.I"
ng-pattern="/^[0-1](\.\d{0,2}){0,1}$/"
my-range="1,1.75"/>
<div role="alert" class="validation-errors"
ng-if="fee.fee_classi.$invalid && fee.fee_classi.$dirty"
ng-messages="fee.fee_classi.$error">
<p ng-message="range">Range should be between 1 to 1.75</p>
<p ng-message="pattern">Format must be 0.00</p>
</div>
</form>
这是指令
app.directive('myRange', myRange);
function myRange() {
var directive = {
bindToController: true,
controller: myRangeCtrl,
controllerAs: 'vm',
// link: link,
restrict: 'A',
scope: {},
require: {
ngModelCtrl: 'ngModel'
}
};
return directive;
}
myRangeCtrl.$inject = ['$element', '$attrs'];
function myRangeCtrl($element, $attrs) {
var vm = this;
vm.min = 0; //default
vm.max = 0; //default
console.clear();
console.log(vm.ngModelCtrl);
var inRange = false;
var rangeVal = $attrs.myRange.split(',');
var userInput;
console.log(rangeVal);
vm.min = JSON.parse(rangeVal[0]);
vm.max = JSON.parse(rangeVal[1]);
$element.on('keypress', function(e) {
console.log(e);
console.log(vm.ngModelCtrl);
//if the pattern is valid then lets check if the user has the proper range
if (vm.ngModelCtrl.$valid) {
vm.ngModelCtrl.$validators.range = function(modelValue, viewValue) {
console.log('modelValue = ' + modelValue);
inRange = _.inRange(modelValue, vm.min, vm.max);
//check if modelValue can be converted to a number with isNaN function
if (isNaN(modelValue)) {
console.error('-VAlue is invalid');
return false;
}
if (angular.isDefined(modelValue) &&
modelValue[modelValue.length - 1] !== '.' &&
modelValue !== '') {
// console.log('modelValue = '+modelValue);
userInput = JSON.parse(modelValue);
if (inRange || userInput === vm.max) {
console.info('VAlue is valid');
//value entered is invalid
return true;
} else {
console.error('VAlue is invalid');
//value entered is valid
return false;
}
}
if (angular.isUndefined(modelValue)) {
return true;
}
//lets do a regex test first
};
}
});
以下是plunkr
答案 0 :(得分:0)
看看这个例子:https://docs.angularjs.org/api/ng/input/input%5Brange%5D 您可能需要稍微调整一下以满足您的需要。