简体   繁体   中英

Angular how to submit and validate form with <a>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <link rel="stylesheet" type="text/css" href="login.css"> -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-messages.min.js"></script>
</head>
<body ng-app="loginApp">
<div class="container">
<div class="login_logo">
</div>
<div class="form_container" ng-controller="loginCtrl" >
<div class="error_msg" ng-if="form_login.username.$dirty" ng-messages="form_login.username.$error">
<div class="alertmsg" ng-message="required">Username and password are required</div>
</div>
<div class="form_left">
<form class="form_login" name="form_login" ng-submit="submitForm()" novalidate>
<div class="usr"><input id="username" name="username" ng-model="username" type="text" autofocus="autofocus" required /></div>
<div class="psw"><input id="password" name="password" ng-model="password" type="password" required /></div>
</form>
</div>
<div class="form_right">
<a class="submit" href="" ng-click="submitForm()">submit</a>
</div>
<div class="clear"></div>

</div>
</div>
<script type="text/javascript">
    var app=angular.module("loginApp",["ngMessages"]);
    app.controller("loginCtrl", function($scope){
        $scope.username = "";
        $scope.password = "";
        $scope.submitForm=function(){
        };
    });
</script>
</body> 
</html>

Now I have a login page as it shows above, I'm trying to do the validation with ngMessages

  1. If I have to use <a> which is outside of form to submit it instead of button, how should I do?
  2. How can I make sure error messages are displayed when username or password is empty, and only after user submit the form.
  3. How to prevent user from resubmitting form with <a> ?

You can check the validation result in your controller function with:

if ($scope.form_login.$valid) {
    ...
}

The form in angularjs will be validated auto. For all form members you can check the doc

To show error messages only after form submit, add a variable '$scope.submitted = true;'. In order to prevent re-submit submit button can be disabled. Please refer following link for detailed explanation. https://scotch.io/tutorials/angularjs-form-validation

Hope it helps.

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