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?

0

3 Answers 3

11

Better do change in ng-submit expression to

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

Best use of angular directive expression.

Sign up to request clarification or add additional context in comments.

2 Comments

me likey this one the best, yes me do
@meffect clean & neat on UI itself..I used this almost in all of my forms..
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"...

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.