Skip to content

Instantly share code, notes, and snippets.

@b4dnewz
Created July 6, 2017 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b4dnewz/92c87b13e908629bc6153650de165844 to your computer and use it in GitHub Desktop.
Save b4dnewz/92c87b13e908629bc6153650de165844 to your computer and use it in GitHub Desktop.
Angular directive to validate input based on maximum words length.
'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