Runar Halse Runar Halse - 4 months ago 37
AngularJS Question

Angularjs prevent form submission when input validation fails

I'm writing a simple login form using angularjs with some client side input validation to check that the user name and password is not empty and longer than three characters. See the below code:

<form name="loginform" novalidate ng-submit="login.submit()" class="css-form">
<fieldset>

<div class="control-group input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" ng-model="login.username" name="username" required ng-minlength="3" placeholder="username" />
</div>

<div class="control-group input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" ng-model="login.password" name="password" required ng-minlength="3" placeholder="" />
</div>

<div class="control-group">
<input class="btn" type="submit" value="Log in">
</div>

</fieldset>
</form>


And the controller:

var controller = function($scope) {

$scope.login = {
submit: function() {

Console.info($scope.login.username + ' ' + $scope.login.password);
}
}

};


The problem is that the
login.submit
function will be called even if the input is not valid. Is it possible to prevent this behaviour?

As a side note I can mention that I use bootstrap and requirejs as well.

Answer

You can do:

<form name="loginform" novalidate ng-submit="loginform.$valid && login.submit()">

No need for controller checks.