Skip to content

Instantly share code, notes, and snippets.

@Imater
Created August 13, 2014 06:04
Show Gist options
  • Save Imater/f9ffabac275720c9807a to your computer and use it in GitHub Desktop.
Save Imater/f9ffabac275720c9807a to your computer and use it in GitHub Desktop.
ValidationDirective
blurFocusDirective = (validationConfig)->
restrict: "A"
require: "?ngModel"
link: ($scope, elm, attr, ctrl) ->
template = $('''
<div class="validate-message">
<div class="arrow_box">
<span class="message"></span>
</div>
</div>
''').hide();
showErrorMessage = (msg) ->
if msg
template.fadeIn(200).find('.message').html(msg)
else
template.fadeOut(200)
getMessage = (errorCode) ->
errorMessageInAttr = attr["#{errorCode}ErrorMessage"]
errorAtDict = validationConfig.dict[errorCode]
return errorMessageInAttr or errorAtDict or ''
findErrors = () ->
errorName = undefined
isNeedShowErrorsNow = ->
$scope.showAllErrors || ($scope.hasFocus && $scope.hasVisited)
if isNeedShowErrorsNow()
errorList = $scope[formName][attr.name].$error
_.each errorList, (value, key) ->
console.info 'error = ', key if value
if value and key != 'required'
errorName = key
else if value and !errorName
errorName = key
showErrorMessage getMessage(errorName)
thisForm = $(elm).closest("form")
formName = thisForm.attr('name')
$scope.$watch "#{formName}.#{attr.name}.$error", (newVal, oldVal) ->
if newVal isnt oldVal
findErrors()
, true
$scope.$watch ()->
ctrl.$viewValue
, (newVal, oldVal) ->
if newVal isnt oldVal
findErrors()
$scope.$watchCollection '[hasFocus,hasVisited,showAllErrors]', (oldVal, newVal) ->
if not _.isEqual(oldVal, newVal)
findErrors()
elm.on "focus", ->
elm.addClass "has-focus"
$scope.$apply ->
$scope.hasFocus = true
$scope.inlineMessage = {}
elm.parent('.input-group').append(template);
elm.on "blur", ->
elm.removeClass "has-focus"
elm.addClass "has-visited"
$scope.$apply ->
$scope.hasFocus = false
$scope.hasVisited = true
$scope.$on 'hideValidationErrors', ()->
$scope.hasFocus = false
$scope.hasVisited = false
$scope.showAllErrors = false
thisForm.find('button[type=submit]').on "click", () ->
$scope.$apply ->
$scope.hasFocus = false
$scope.hasVisited = false
$scope.showAllErrors = true
return unless ctrl
angular.module(window.appName).directive "showVerifyErrors", blurFocusDirective
validationSubmit = [
"$injector"
($injector) ->
$timeout = $injector.get("$timeout")
$parse = $injector.get("$parse")
return (
priority: 1 # execute before ng-click (0)
require: "?ngClick"
link: postLink = (scope, element, attrs) ->
form = $parse(attrs.validationSubmit)(scope)
$timeout ->
# Disable ng-click event propagation
element.off "click"
element.on "click", (e) ->
e.preventDefault()
if form.$valid
scope.$broadcast 'hideValidationErrors'
$parse(attrs.ngClick) scope
)
]
angular.module(window.appName).directive "validationSubmit", validationSubmit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment