javascript - $setValidity not working -
i have condition if user enters either contact number or email form should considered valid, make work tried use $setvalidity not working, below code:
if($scope.contact.contactnumber || $scope.contact.email) { $scope.addcontactform.contactnumber.$setvalidity('required', false); $scope.addcontactform.email.$setvalidity('required', false); // in console show invalid true & valid false console.log('scope:', $scope.addcontactform); }
it because doing wrong. should pass true second argument if want set field valid state. read documentation.
below example how use $setvalidity correctly.
angular.module('app', []); angular.module('app').controller('example', function () { this.setvalid = () => { this.form.contactnumber.$setvalidity('required', true); this.form.email.$setvalidity('required', true); }; this.setinvalid = () => { this.form.contactnumber.$setvalidity('required', false); this.form.email.$setvalidity('required', false); }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script> <div ng-app="app" ng-controller="example example"> <form name="example.form"> <input type="text" name="contactnumber" ng-model="contactnumber" required><br> <input type="text" name="email" ng-model="email" require> </form> <br> $invalid = {{example.form.$invalid}}, $valid = {{example.form.$valid}}<br> <button type="button" ng-click="example.setvalid()">set valid</button> <button type="button" ng-click="example.setinvalid()">set invalid</button> </div>
Comments
Post a Comment