Nina Morena Nina Morena -4 years ago 279
AngularJS Question

How To Change Select to ng-invalid in Angular

I have an expiration month and year that appears in a form using a select input field. When a user clicks the month and year ng-change fires a function checkDate() to validate. I use the console to return if the date is valid or invalid. I also show the error message stating the expiration date is invalid. However, I am unable to give the select element an invalid state even if the form is not valid. The class changes from ng-invalid to ng-valid on the select element even if the date is incorrect which ultimately makes my form valid. How do I apply the invalid class to the select element if the select field is invalid?

HTML

<div>
<label for="exp_year">Exp Year</label>
<select id="exp_year" class="form-control" ng-model="exp_year" ng-change="checkDate()" required>
<option value="" disabled><span class="pull-left">Year</span></option>
<option value="{{ year }}" ng-repeat="year in years">{{ year }}</option>
</select>
<i class="material-icons pull-right select-icon">arrow_drop_down</i>
</div>

<small class="text-danger">{{errMessage}}</small>


JS

$scope.checkDate = function () {
if (!($scope.exp_month && $scope.exp_month)) return;
if ($scope.exp_month <= currentMonth && $scope.exp_year <= currentYear){
console.log('this form is invalid')
$scope.errMessage = 'Please enter a valid expiration date';
return true
} else {
console.log('this form is valid')
$scope.errMessage = '';
return false
}
}

Answer Source

Instead of validating form inputs by adding valid/invalid classes, there is a better way of performing custom validation:

Using $scope.formName.inputName.$setValidity("reason", false) (Angular Docs)

So when you find your values are invalid (month-year combination expired in your case..), you can set validity to false. and when it is valid again, to true.

And you can use $scope.formName.$valid to know whether your form is valid or not. Based on that you can perform your further action.

Working plunker made your example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download