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?

ocket8888
  • 1,060
  • 12
  • 31
rwacarter
  • 1,915
  • 1
  • 14
  • 25

3 Answers3

11

Better do change in ng-submit expression to

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

Best use of angular directive expression.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
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"...
Arūnas Smaliukas
  • 3,231
  • 6
  • 27
  • 46
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

kinetix
  • 11
  • 2