简体   繁体   中英

Is it possible to use ng-blur and ng-submit together in AngularJS?

I tried to validate two fields with ng-blur and it worked fine.But i need to validate fields both in ng-blur and ng-submit.

The validation should work by both in focus and clicking button.

Html :

<form name="myForm" ng-submit="submit()" novalidate>
   <input type="text" placeholder="enter your email" name="email"
      ng-model="email" ng-blur="visitedEmail = true" required
      ng-pattern="pattern"
      ng-class="{error: submitted && myForm.email.$invalid }" /> 
   <input type="password" placeholder="enter your password" name="password"
      ng-blur="visitedPassword = true" required ng-model="password"
      ng-class="{error: submitted && myForm.password.$invalid }" />
   <section >
      <input type="submit" value="Sign in" /> 
   </section>
</form>

Js file :

   $scope.submit = function(){
        // Set the 'submitted' flag to true
        $scope.submitted = true;
        // Send the form to server
        // $http.post    
   };

Could anyone tel whats wrong with my code..

Removed novalidate from form tag. Validates now. Add a validate function manually in submit function if you wabt as I mentioned in comment of the question. See the plnkr

<form name="myForm" ng-submit="submit()">
 <input type="text" placeholder="enter your email" name="email"
        ng-model="email" ng-blur="visitedEmail = true" required
        ng-pattern="pattern"
        ng-class="{error: submitted && myForm.email.$invalid }" /> 
  <input type="password" placeholder="enter your password" name="password"
        ng-blur="visitedPassword = true" required ng-model="password"
        ng-class="{error: submitted && myForm.password.$invalid }" />
  <section >
    <input type="submit" value="Sign in" /> 
  </section>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM