Last active
December 20, 2015 22:59
-
-
Save oivoodoo/6209466 to your computer and use it in GitHub Desktop.
Custom validator for angularjs
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
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 | |
} |
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
= 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