Created
July 6, 2017 14:18
-
-
Save b4dnewz/92c87b13e908629bc6153650de165844 to your computer and use it in GitHub Desktop.
Angular directive to validate input based on maximum words length.
This file contains hidden or 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
'use strict' | |
###* | |
# @ngdoc directive | |
# @name app.directive:ngMaxwords | |
# @description Angular directive to validate input based on maximum words length. | |
# # ngMaxwords | |
### | |
angular.module 'app' | |
.directive 'ngMaxwords', -> | |
restrict: 'A' | |
require: '?ngModel' | |
link: (scope, element, attrs, ctrl) -> | |
if (!ctrl) | |
return | |
maxwords = 0 | |
attrs.$observe('ngMaxwords', (value) -> | |
intval = parseInt(value) | |
maxwords = angular.isNumber(intval) ? intval : -1 | |
ctrl.$validate() | |
) | |
ctrl.$validators.maxwords = (modelValue, viewValue) -> | |
(maxwords < 0) || ctrl.$isEmpty(viewValue) || (viewValue.match(/\S+/g).length <= maxwords) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment