Created
March 5, 2015 07:01
-
-
Save anonymous/e5a9c60e73f1b69792b1 to your computer and use it in GitHub Desktop.
AngularJS: Mutually Exclusive Input Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html ng-app="myApp"> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> | |
<script> | |
var myApp = angular.module("myApp",[]) ; | |
myApp.controller('MyCtrl', ['$scope', function($scope) { | |
$scope.formModel = {}; | |
}]); | |
myApp.directive('mutuallyExclusive', function() { | |
return { | |
require: 'ngModel', | |
link: function(scope, elem, attrs, ctrl) { | |
var xorValidator = function(value) { | |
var form = scope[attrs.form]; | |
var theOther = form[attrs.mutuallyExclusive]; | |
var otherValue = theOther.$modelValue; | |
var a = (value != null && typeof(value) !== 'undefined' && value != '') ? true: false; | |
var b = (otherValue != null && typeof(otherValue) !== 'undefined' && otherValue != '') ? true: false; | |
var xor = ( a || b ) && !( a && b ); | |
console.log("XOR = " + xor); | |
ctrl.$setValidity('field', xor); | |
theOther.$setValidity('field', xor); | |
return value; | |
}; | |
ctrl.$parsers.unshift(xorValidator); | |
} | |
}; | |
}); | |
</script> | |
</head> | |
<body ng-controller="MyCtrl"> | |
<form id="myForm" name="myForm" method="post" novalidate="novalidate"> | |
<select id="select1" name="select1" form="myForm" ng-model="formModel.select1" mutually-exclusive="text1"> | |
<option value="0">Value 0</option> | |
<option value="1">Value 1</option> | |
</select> | |
<input type="number" id="text1" name="text1" form="myForm" ng-model="formModel.text1" mutually-exclusive="select1"/> | |
<input type="submit" ng-disabled="myForm.$invalid || (myForm.select1.$pristine && myForm.text1.$pristine)" /> | |
</form> | |
myForm.$invalid: {{myForm.$invalid}}<br /> | |
{{myForm.text1.$pristine}} | |
<pre>select1.$invalid: {{myForm.select1 | json}} | |
</pre> | |
<pre>text1.$invalid: {{myForm.text1 | json}}</pre> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment