AngularJS 前端验证指令
- var rcSubmitDirective = {
- 'rcSubmit': function ($parse) {
- return {
- restrict: "A",
- require: [ "rcSubmit", "?form" ],
- controller: function() {
- this.attempted = false;
- var formController = null;
- this.setAttempted = function() {
- this.attempted = true;
- };
- this.setFormController = function(controller) {
- formController = controller;
- };
- this.needsAttention = function(fieldModelController) {
- if (!formController) return false;
- if (fieldModelController) {
- return fieldModelController.$invalid && (fieldModelController.$dirty || this.attempted);
- } else {
- return formController && formController.$invalid && (formController.$dirty || this.attempted);
- }
- };
- },
- compile: function() {
- return {
- pre: function(scope, formElement, attributes, controllers) {
- var submitController = controllers[0];
- var formController = controllers.length > 1 ? controllers[1] : null;
- submitController.setFormController(formController);
- scope.rc = scope.rc || {};
- scope.rc[attributes.name] = submitController;
- },
- post: function(scope, formElement, attributes, controllers) {
- var submitController = controllers[0];
- var formController = controllers.length > 1 ? controllers[1] : null;
- var fn = $parse(attributes.rcSubmit);
- formElement.bind("submit", function(event) {
- submitController.setAttempted();
- if (!scope.$$phase) scope.$apply();
- if (!formController.$valid) return;
- scope.$apply(function() {
- fn(scope, {
- $event: event
- });
- });
- });
- }
- };
- }
- };
- }
- };
验证通过
- <form name="loginForm" novalidate
- ng-app="LoginApp" ng-controller="LoginController" rc-submit="login()">
- <div class="form-group"
- ng-class="{'has-error': rc.loginForm.needsAttention(loginForm.username)}">
- <input class="form-control" name="username" type="text"
- placeholder="Username" required ng-model="session.username" />
- <span class="help-block"
- ng-show="rc.form.needsAttention(loginForm.username) && loginForm.username.$error.required">Required</span>
- </div>
- <div class="form-group"
- ng-class="{'has-error': rc.loginForm.needsAttention(loginForm.password)}">
- <input class="form-control" name="password" type="password"
- placeholder="Password" required ng-model="session.password" />
- <span class="help-block"
- ng-show="rc.form.needsAttention(loginForm.password) && loginForm.password.$error.required">Required</span>
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-primary pull-right"
- value="Login" title="Login">
- <span>Login</span>
- </button>
- </div>
- </form>
样式如下
前端验证通过会调用login()