Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS form validation is always true

loginForm.$valid is always return true, even when required fields are not filled out. I was unable to find a similar problem anywhere.

<form name="loginForm" 
      class="form-login" 
      ng-submit="loginForm.$valid && loginCtrl.login(navCtrl)" 
      novalidate>

    <div class="form-group">
        <label for="email">Username:</label>
        <input type="email" class="form-control" id="username" placeholder="Enter username" required>
    </div>

    <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd" placeholder="Enter password" required>
    </div>

    <div class="form-group text-right">
        <a href="#">Forgot password?</a>
    </div>
    <div>Login form is {{loginForm.$valid}}</div>
    <button type="submit" class="btn btn-default">Login</button>
</form>

Any help is appreciated.

like image 861
cohenadair Avatar asked May 27 '15 15:05

cohenadair


2 Answers

Form validation and related flags will be set only if you have ng-model controllers assigned to the respective controls. So assign ng-model directive to them. Also instead of using id, you could use name. It will then be used as alias (property names) for the respective ng-model controller assigned on the formController instance (ex: loginForm.username.$valid ).

<div class="form-group">
        <label for="email">Username:</label>
        <input type="email" class="form-control" 
         ng-model="ctrl.userName"
         name="username" placeholder="Enter username" required>
    </div>

    <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" 
           ng-model="ctrl.password"
           name="pwd" placeholder="Enter password" required>
    </div>
like image 160
PSL Avatar answered Sep 18 '22 02:09

PSL


I had this problem too. The answer was required syntax wasn't there.
So it was always valid to submit the form.

like image 44
omarhabeh Avatar answered Sep 20 '22 02:09

omarhabeh