【问题标题】:Form error upon submitting提交时表单错误
【发布时间】:2017-01-12 14:16:52
【问题描述】:

我有一个表格,其中有一个必填字段和一个非必填字段。成功提交表单向服务器发送数据后,我清除了两个输入字段模型中的数据。但是,通过这样做,必填字段变为红色并显示错误This field is required。提交表单并清除其数据后,如何保持必填字段无错误。我希望它仅在用户尝试使用 EMPTY REQUIRED FIELD 提交表单时显示错误。

<form name="myForm">
    <div layout="row" layout-align="center center" flex="100">
        <md-input-container class="md-block" flex="40">
            <input required type="text" placeholder="Book Name"
                   ng-model="bookName"
            />

            <div ng-messages="$error">
                <div ng-message="required">This is required.</div>
            </div>
        </md-input-container>

        <span flex="10"></span>

        <md-input-container class="md-block" flex="40">
            <input type="text" placeholder="Theme"
                   ng-model="theme"
                   enter-pressed=""/>
        </md-input-container>
    </div>
</form>

<md-button class="md-raised md-primary" flex="none" type="submit"
           ng-click="onSubmitClicked()">Submit
</md-button>


    $scope.onSubmitClicked = function() {
        $scope.bookName = ""; // this causes the REQUIRED FIELD ERROR AFTER I SUBMIT THE FORM
        $scope.theme  = "";
    };

【问题讨论】:

    标签: javascript angularjs forms angular-material mean-stack


    【解决方案1】:

    添加到 Asiel 的答案中,您应该在清除模型后执行以下操作。

                     if(form){ //make sure a form is passed as parameter
                         form.$setPristine(); //this will reset the form to its original state
                         form.$setUntouched();
                     }
    

    form.$setUntouched 会将表单设置为未触及状态,从而删除错误消息。

    【讨论】:

      【解决方案2】:

      请执行以下操作:

      <form name="myForm" ng-submit="onSubmitClicked(myForm)">
      
        <md-button class="md-raised md-primary" flex="none" type="submit">Submit</md-button>
      </form>
      
      
      $scope.onSubmitClicked = function(form) {
          if (form.$valid) {
                // do what you have to do, the form is validated
              return;
          }
      
          // dont do anythign the form will flag ans $invalid and $submitted and the error messages will show
          return;
      
      };
      

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 2013-02-17
        • 2011-07-28
        • 2014-02-25
        • 2018-11-24
        • 2017-08-24
        • 2011-01-06
        相关资源
        最近更新 更多