【问题标题】:Angular how to submit and validate form with <a>Angular 如何使用 <a> 提交和验证表单
【发布时间】:2016-01-14 02:17:40
【问题描述】:
<!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>

现在我有一个如上所示的登录页面,我正在尝试使用 ngMessages 进行验证

  1. 如果我必须使用表单外的&lt;a&gt;而不是按钮来提交它,我该怎么办?
  2. 如何确保在用户名或密码为空时显示错误消息,并且仅在用户提交表单后显示。
  3. 如何防止用户使用&lt;a&gt;重新提交表单?

【问题讨论】:

  • 没有意义。解释为什么不使用表单按钮而不是&lt;a&gt;。将表单标签移动到左右两边是一个小问题。

标签: javascript angularjs


【解决方案1】:

要仅在表单提交后显示错误消息,请添加变量“$scope.submitted = true;”。 为了防止重新提交提交按钮可以禁用。 请参阅以下链接以获取详细说明。 https://scotch.io/tutorials/angularjs-form-validation

希望对你有帮助。

【讨论】:

    【解决方案2】:

    你可以在你的控制器函数中检查验证结果:

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

    angularjs 中的表单将自动验证。对于所有表单成员,您可以查看doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 2023-04-03
      • 2019-04-08
      • 1970-01-01
      相关资源
      最近更新 更多