简体   繁体   中英

How to implement form validation with Angular JS and Bootstrap?

At a user registration web form I validate via ajax whether a username already exists in DB. When a username already exists, the corresponding input-text will go .has-error class.

Edit

I changed the ng-class attribute to {'has-error':signup.userUnavaliable()} but even though that the input is not seemly getting such class, in other words the mail input text is not getting red.

I place the directive at the wrapper as this is how the Bootstrap docs tell it.

This is how my form looks like now:

<form class="form-inline" role="form">
  <div class="form-group" ng-class="{'has-error':signup.userUnavaliable()}">
    <input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)">
  </div>
  <div class="form-group">
    <input type="password" class="form-control input-lg" placeholder="Contraseña" ng-nodel="signup.password">
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" ng-model="signup.role" value="admin"> Administrador
    </label>
  </div>
  <button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable">Registrar</button>
</form>

And this is my Controller:

app.controller('SignUpController',function ($scope, $http) {

    $scope.userUnavaliable = function() {

        return $scope.unavaliable
    }

    $scope.print = function(msg) {

        console.log(msg)
    }

    this.userExists = function(mail) {

        if (mail) {

            var who = $http.get("/existingUsers/"+mail)

            who.success(function(data,status, headers, config) {
                if (data.mail) {
                    $scope.unavaliable = true
                    console.log(data.mail + " ya existe en la DB")
                }
                else{
                    $scope.unavaliable = false
                }
            });

            who.error(function(data, status, headers, config) {
                    alert("AJAX failed!");
            })
        }

    }

})

Also, I'm trying to disable the button and it's not gettin such effect, so I think my controller has any issue.

As given in bootstrap validation states, if you want your label color to be changed according to the validation state of the input, you will have to apply ng-class on that.

Here is the sample code that I had written a little while. Please note that to take advantage of Angular JS validation states on form elements, you need to provide name to all input types.

This code would turn the input box plus label color red or green depending upon the validation state.

<div class="form-group" 
             ng-class="( newProfileForm.email.$dirty ? (newProfileForm.email.$valid ? 'has-success has-feedback' : 'has-error has-feedback' ) : ' ')"
             >

                <label class="col-sm-4 control-label">Email</label>

                <div class="col-sm-6">
                    <input type="email" name="email" class="form-control" ng-model="user.mail" ng-required='true'>    

                    <!-- Invalid Span -->           
                    <span ng-if='newProfileForm.email.$invalid && newProfileForm.email.$dirty' class="glyphicon glyphicon-remove form-control-feedback"></span>

                    <!-- Valid Span -->
                    <span ng-if='newProfileForm.email.$valid' class="glyphicon glyphicon-ok form-control-feedback"></span>
                    <p ng-show="newProfileForm.email.$invalid && newProfileForm.email.$dirty" class="bg-danger pad">Please enter valid email.</p>
                </div>           
        </div>

[EDIT] Explanation for name attribute. Angular makes use of name attribute to determine the state of the input control. So, if you have a input control with name username . Even your form should have a name for angular validation states.

AngularJS would use the fallowing variables to check its validation state.

formname.username.$valid = if username is alright according to validation rules.

formname.username.$invalid = if username is invalid

formname.username.$dirty = if user has edited the input box

formname.username.$pristine = if user has not edited the input box.

Angular makes use of name attribute for validaiton.

And if you want your button to be disabled depending upon the availability of the user. Use something like

<button class="btn btn-default" ng-disabled="unavaliable">Submit</button>

尝试

 <div class="form-group" ng-class="{'has-error':signup.userUnavaliable()}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM