Skip to content

Instantly share code, notes, and snippets.

@oivoodoo
Last active December 20, 2015 22:59
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 oivoodoo/6209466 to your computer and use it in GitHub Desktop.
Save oivoodoo/6209466 to your computer and use it in GitHub Desktop.
Custom validator for angularjs
admin.directive 'akRequired', ->
isEmpty = (value) ->
angular.isUndefined(value) || value is '' || value is null || value isnt value
compile = ($element, $attributes) ->
title = 'Required!'
template = "<span class = 'error' ng-show = \"form['#{$attributes.akRequired}'].$error.akRequired\">#{title}</span>"
$(template).insertAfter($element)
($scope, $element, $attributes, $control) ->
validator = (isRequired, value) ->
if isRequired && isEmpty(value)
$control.$setValidity('akRequired', false)
return
else
$control.$setValidity('akRequired', true)
return value
validate = ->
# isRequired is always true in case if we don't have condition dependency
isRequired = $scope.$eval($attributes.if || 'true')
validator(isRequired, $control.$viewValue)
$scope.$watch($attributes.watch, validate)
# in case if we have a condition dependency we should watch them as well
# and rerun validation.
if $attributes.if?
$scope.$watch($attributes.if, validate)
return {
restrict: 'A'
require: 'ngModel'
compile: compile
replace: false
}
= f.text_field :name,
:'ng-model' => 'app.name',
:'ak-required' => 'app[name]'
= f.text_field :platform, 'ng-model' => 'app.platform'
= f.text_field :apple_id,
:'ng-model' => 'app.apple_id',
:'ak-required' => 'app[apple_id]',
:if => "app.platform == 'ios'"
= f.text_field :android_id,
:'ng-model' => 'app.android_id',
:'ak-required' => 'app[android_id',
:if => "app.platform == 'android'"
= f.submit "Submit", 'ng-disabled' => 'form.$invalid'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment