提交时表格错误

时间:2017-01-12 14:16:53

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

我有一个表单,其中有一个必填字段和一个非必填字段。成功将表单发送数据提交到服务器后,我清除了两个输入字段模型中的数据。但是,通过这样做,必填字段变为红色并显示错误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  = "";
    };

2 个答案:

答案 0 :(得分:0)

根据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会将表单设置为未触摸状态,从而删除错误消息。

答案 1 :(得分:0)

请执行以下操作:

<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;

};