Skip to content

Instantly share code, notes, and snippets.

@roden0
Created May 27, 2013 10:18
Show Gist options
  • Save roden0/5656349 to your computer and use it in GitHub Desktop.
Save roden0/5656349 to your computer and use it in GitHub Desktop.
Angular JS. Validation.
<form data-ng-app="form-example" class="row form-horizontal" novalidate>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="email" id="inputEmail" placeholder="Email" data-ng-model="email" required>
<div class="input-help">
<h4>Invalid Email</h4>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input data-ng-model="password" class="immediate-help" password-validate required type="password" id="inputPassword" placeholder="Password">
<div class="input-help">
<h4>Password must meet the following requirements:</h4>
<ul>
<li data-ng-class="pwdHasLetter">At least <strong>one letter</strong></li>
<li data-ng-class="pwdHasNumber">At least <strong>one number</strong></li>
<li data-ng-class="pwdValidLength">At least <strong>8 characters long</strong></li>
</ul>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Create Account</button>
<button class="btn" disabled>Create Account</button>
</div>
</div>
</form>
var app = angular.module('form-example', []);
app.directive('passwordValidate', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
scope.pwdValidLength = (viewValue && viewValue.length >= 8 ? 'valid' : undefined);
scope.pwdHasLetter = (viewValue && /[A-z]/.test(viewValue)) ? 'valid' : undefined;
scope.pwdHasNumber = (viewValue && /\d/.test(viewValue)) ? 'valid' : undefined;
if(scope.pwdValidLength && scope.pwdHasLetter && scope.pwdHasNumber) {
ctrl.$setValidity('pwd', true);
return viewValue;
} else {
ctrl.$setValidity('pwd', false);
return undefined;
}
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment