提交表单或字段为脏时显示验证消息 - 提交时,两个验证消息都是自定义和默认显示

时间:2015-05-22 19:46:33

标签: javascript jquery html angularjs

我对自定义消息有两个问题:

首先,我第一次加载页面时会显示错误消息,我只想在提交表单或字段脏(修改)时显示它们。

这是我的代码:

 <form class="form-horizontal name="newEventForm">
   <div ng-messages="newEventForm.Name.$error" style="color: maroon" role="alert" >
   <div ng-message="required">You did not enter a field</div>
                                <div ng-message="minlength">Your field is too short</div>
   <div ng-message="maxlength">Your field is too long</div>
   </div>
 </form>

我遇到的第二个问题是,当我提交表单时它会显示两条消息,即自定义消息和默认的require消息。 见上图(您没有输入字段是我的自定义消息):

enter image description here

我希望在表单有效时执行ajax调用

 $scope.ajaxSend = function (action, dataoSend, newEventForm) {
    if (newEventForm.$valid) {
        $.ajax({
            type: 'POST',
            url: "/" + _controller + "/" + action,
            contentType: 'application/json; charset=utf-8',                
            success: function (data) {
                $scope.table.reload();
            },
            error: function () {
            }
        });
    }
};

1 个答案:

答案 0 :(得分:2)

要防止默认验证,请尝试将novalidate属性添加到表单中:

<form class="form-horizontal name="newEventForm" novalidate>`

您可以利用表单的$submitted属性和每个字段的$dirty属性来有条件地显示消息。像这样:

<div ng-show="newEventForm.$submitted || newEventForm.Name.$dirty" ng-messages="newEventForm.Name.$error" style="color: maroon" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
   <div ng-message="maxlength">Your field is too long</div>
</div>
相关问题