javascriptangularjsformsangularjs-forms

AngularJS - Prevent submission of a form if it is invalid


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?


Solution

  • Better do change in ng-submit expression to

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

    Best use of angular directive expression.