Skip to content

Instantly share code, notes, and snippets.

@brachycera
Last active December 30, 2015 17:20
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 brachycera/c8fbbaceed5393d6ddc2 to your computer and use it in GitHub Desktop.
Save brachycera/c8fbbaceed5393d6ddc2 to your computer and use it in GitHub Desktop.
Angular 1.3.x Directive to fetch minlength Value from Input Text Field and show the Value in the ng-message for minlength Errors
<small class="error" ng-message="minlength" validate-minlength>Please enter at least {{requiredMinLength}} characters</small>
<form name="userRegForm">
<fieldset>
<legend>User Registration</legend>
<label>
Username
<input type="text"
ng-model="user.username"
name="user"
minlength="4"
required
>
<div role="alert"
ng-show="userRegForm.user.$invalid && userRegForm.user.$dirty"
ng-messages="userRegForm.user.$error"
ng-messages-include="errors_tpl.html"
></div>
</label>
<button type="submit" class="button postfix">Save</button>
</fieldset>
</form>
(function ( ) {
'use strict';
var app = angluar.module('flyweb');
app.directive('validateMinlength', validateMinlength);
app.directive('minlength', minlength);
function validateMinlength( ) {
return {
restrict : 'A',
require : '^form',
link : linkFunction
};
function linkFunction( scope, element, attrs, ctrl ) {
scope.$watch( error, errorMsg );
function error( ) {
return ctrl.$error.minlength;
}
function errorMsg( ) {
if ( ctrl.$error.minlength ){
scope.requiredMinLength = ctrl.$error.minlength[0].$minlength;
}
}
}
}
function minlength( ) {
return {
restrict : 'A',
require : '^ngModel',
link : function ( scope, element, attrs, ngModelCtrl ) {
ngModelCtrl.$minlength = attrs.minlength;
}
};
}
}( ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment