如何在angularjs中使用ngMessages表单验证

时间:2018-08-20 17:55:22

标签: javascript angularjs forms

我是angularjs的新手,我需要帮助找出我做错了什么。我正在使用ngMessages进行表单验证,但是表单提交无法正常工作。

这是我的代码:

angular.module("myapp", ["ngMessages"])
p {
  color: red;
}
<script src="https://code.angularjs.org/1.7.2/angular.js"></script>
<script src="https://code.angularjs.org/1.7.2/angular-messages.js"></script>
<div ng-app="myapp">
  <form name="myform" method="post" novalidate>

    <label>Username</label>
    <input type="text" name="username" ng-model="inputName" ng-minlength="6" ng-maxlength="12" ng-pattern="/^\w+$/" required>
    <div ng-messages="myform.username.$error">
      <p ng-message="minlength">Username should have at least 6 characters.</p>
      <p ng-message="maxlength">Username should have at most 12 characters.</p>
      <p ng-message="required">Providing a username is mandatory.</p>
      <p ng-message="pattern">Username can only be alphanumeric with an optional underscore.</p>
    </div>
    <input type="submit" name="submit">
  </form>
</div>

1 个答案:

答案 0 :(得分:1)

您需要基本使用ng-submit

<form name="myform" ng-submit="submit(myform.$valid)" novalidate>

然后在您的控制器中,需要定义方法submit

$scope.submit = function(isValid){
    if(isValid){
       $http.post('your_post_url_here',your_form_data).then(function(success){
             // success message
       })
    }
}