Skip to content

Instantly share code, notes, and snippets.

@brachycera
Last active Dec 30, 2015
Embed
What would you like to do?
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