Runar Halse Runar Halse - 1 year ago 101
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">

<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 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 class="control-group">
<input class="btn" type="submit" value="Log in">


And the controller:

var controller = function($scope) {

$scope.login = {
submit: function() {$scope.login.username + ' ' + $scope.login.password);


The problem is that the
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 Source

You can do:

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

No need for controller checks.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download