使用ng-change,AngularJS进行日期输入验证 [英] Date input validation using ng-change, AngularJS
问题描述
我在页面中使用AngularJS和 AngularJS引导程序。我有一个日期选择器指令,如下所示:
I's using AngularJS and AngularJS bootstrap in my page. I have a date picker directive that looks like this:
<div class="form-group {{dateStatus.class}}">
<p class="input-group">
<input type="text" id="inpDate" class="form-control"
datepicker-popup="dd-MMMM-yyyy" ng-model="task.date"
is-open="datePickerStatus.isOpen" min-date="minDate"
datepicker-options="dateOptions" ng-required="true"
close-text="Close" placeholder="Due date"
ng-change="checkDateValidity()"
/>
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="openDatePicker($event)"
>
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</p>
</div>
要验证日期输入,在控制器中,我具有以下功能:
To validate the date input, in my controller I have the following function:
$scope.checkDateValidity = function(){
var date,
isValid,
taskDate;
taskDate = $scope.task.date;
date = new Date(taskDate);
isValid = !isNaN(date);
if(isValid) {
$scope.addButtonState.isOk = true;
$scope.dateStatus.class = '';
}
else{
$scope.addButtonState.isOk = false;
$scope.dateStatus.class = 'has-error';
}
}
一切正常,可以检查插入的日期是否有效,但是问题是,当日期输入留空(或从有效状态更改为空白)
时,我也希望它可以接受,但是由于空输入和无效日期都是未定义
我不知道如何在两种情况之间声明。
everything works fine for checking if the date inserted is valid, but the problem is that when the date input is left blank(or changed from a valid state to blank)
I want it to be acceptable too, but since both empty input and invalid date are undefined
I don't know how to declare between the cases.
我还想到了这样直接读取输入文本:
I also thought of reading the input text directly like this:
document.getElementById('inpDate').value
,但是当值更改时会触发ng-change,而我留下的前一个值现在已经无用了...
but the ng-change is fired when the value is changed and I'm left with the previous value which is useless now...
感谢您的时间和答复。
推荐答案
您可以轻松地验证 #inpDate $通过将验证程序回调绑定到
change
和 keyup
事件来绑定c $ c>值,然后在触发回调时,您可以检查输入的有效性。
You can easily validate #inpDate
value by binding validator callback to both change
and keyup
events, then when your callback triggered you can check the validity of your input.
$timeout(function(){
angular
.element(document.getElementById('inpDate'))
.bind('keyup change', function(){
var inputValue,
customDate,
isValid;
inputValue = this.value;
if(inputValue != ''){
customDate = new Date(inputValue);
isValid = !isNaN(customDate);
if(isValid){
console.log('Valid');
// do something
}
else{
console.log('Invalid');
// do something else
}
}
else{
console.log('Empty');
// do something else
}
});
}, 400);
请确保您已注入 $ timeout
在您的控制器中。
Please make sure that your have injected $timeout
in your controller.
这篇关于使用ng-change,AngularJS进行日期输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!