AngularJS - Prevent submission of a form if it is invalid [duplicate]
Asked Answered
S

3

5

I have created an isolated case of my issue: http://plnkr.co/edit/6LXW5TG76LC9LNSrdpQC

Here is the code of the isolated case:

<!DOCTYPE html>
<html ng-app="App">

    <head></head>

    <body ng-controller="ExampleController">
    
    <form name="form" ng-submit="submit()" novalidate>
        <input type="number" name="number" ng-model="number" required><br>
        <span ng-show="form.number.$error.required && form.number.$touched">Required<br></span>
        <span ng-show="form.number.$error.number">Not a number<br></span>
        <input type="submit">
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    
    <script>
        
        var App = angular.module('App', []);
        
        App.controller('ExampleController', function($scope) {
        
        $scope.submit = function() {
            alert('send to server: ' + $scope.number);
        }
        
        });
        
        App.run();
        
    </script>
    </body>
</html>

Basically, the example contains a number field, and beneath it are error messages that show when the input is invalid (empty or not a number).

But the form will still submit, and although the field value is set to 'undefined' if it is not valid, I would prefer a way of checking if the form is valid before sending to the server (the alert box in this example).

So my question is - In AngularJS, is there a way of checking if a form is valid from within a controller? Or another way to prevent a form from submitting if it is invalid?

Security answered 17/1, 2015 at 11:0 Comment(0)
F
11

Better do change in ng-submit expression to

ng-submit="form.$valid && submit()"

Best use of angular directive expression.

Fauman answered 17/1, 2015 at 11:50 Comment(2)
me likey this one the best, yes me doDorladorlisa
@meffect clean & neat on UI itself..I used this almost in all of my forms..Fauman
T
5

http://plnkr.co/edit/kqLUJpjt0n0anJxzm6en?p=preview

what you need is

if ($scope.form.$valid) {
    //submit to server
}

where form is form name

<form name="form"...
Tedric answered 17/1, 2015 at 11:4 Comment(0)
L
1

You can try with ng-disabled directive

      <button type="submit" ng-disabled='number==null'>Submit</button>

In that way you can avoid adding additional code

Leaven answered 17/1, 2015 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.