1

When I click submit button, the form gets submitted instead of validating for the required fields.

Markup

<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-controller="myCtrl">

<head>
    <meta charset="UTF-8">
    <title>HTML 5</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
    <div id="container">
        <p ng-show="msg"> {{ msg }}</p>
        <form name="myForm" novalidate ng-submit="valid()">
            <p> Name <input type="text" name="name" id="" ng-model="user.name" ng-required=true></p>
            <p ng-show="myForm.name.$invalid && myForm.name.$touched">name is required</p>
            <p> Email <input type="email" name="email" id="" ng-model="user.email" ng-required=true> </p>
            <p ng-show="myForm.email.$invalid && myForm.email.$touched">must be a valid email</p>

            <input type="submit" value="submit">
        </form>
    </div>
    <script>
      angular.module('myApp', [])
         .controller('myCtrl', ['$scope', function($scope) {
            $scope.valid = function() {
            $scope.msg = "form submitted";
         }
      }]);
    </script>
</body>
</html>

Any help would appreciated. Thanks

3 Answers 3

1

Shortest way to call function if form is validate is dictated below, which will fired up valid function only when form is valid.

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

Or other way would be check myForm object in $scope, because when you give name="myForm" on form, angular does create a object inside scope that have all the information field information inside that object.

$scope.valid = function(){
   if($scope.myForm.$valid){
      //form is valid
      //do $http.post call if you wanted to submit form data
   }
   else {
      alert('form is invalid');//some how notify user that form is invalid.
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can just disable the submit button using:

ng-disabled="boolean expression"

in your case it will be simply:

<input type="submit" value="submit" ng-disabled="!myForm.$valid">

Comments

0

Try to put:

$scope.valid=function() {
  if ($scope.myForm.isValid()) $scope.msg="form submitted";
  else $scope.msg="form with errors";
}

hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.