我有一个表单,其中的组件绑定到ng-messages验证系统,并使用jquery-steps分成几个部分。
当用户按下jquery-steps
按钮从一个部分导航到部分时,我需要触发验证。这些是简单的按钮,不提交表单。在代码中,绑定到各部分之间的导航,我可以清楚地看到数据是否输入以及是否正确:例如,我可以成功引用$scope.eventForm.title.$valid
。但是,我想在数据不正确时强制显示验证消息。目前它们仅在我点击任一输入后出现,但我想从控制器触发它们。有可能吗?
视图的html:
<div ng-controller="eventDetailsController as ctrl" ng-cloak>
<md-content class="md-padding" layout-xs="column" layout="row" layout-align="center center">
<div flex-xs flex-gt-xs="70" layout="column">
<form name="eventForm">
<div wizard="{content: '#format-toolbar-options', position: 'top'}" id="event_wizard">
<h3>Basic data</h3>
<section>
<md-card>
<img ng-src="{{imagePath}}" class="md-card-image" alt="Washed Out"/>
<md-card-title>
<md-card-title-text>
<h3>New event</h3>
</md-card-title-text>
</md-card-title>
<md-card-content>
<div layout="row">
<md-input-container class="md-block" flex="50">
<label>Title</label>
<input md-maxlength="30" required md-no-asterisk name="title" ng-model="event.title">
<div ng-messages="eventForm.title.$error">
<div ng-message="required">This is required.</div>
<div ng-message="md-maxlength">The title must be less than 30 characters long.</div>
</div>
</md-input-container>
</div>
<div layout="row">
<md-input-container class="md-block">
<label>Contacts</label>
<input required type="email" name="contacts" ng-model="event.contacts"
minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/" />
<div ng-messages="eventForm.contacts.$error" role="alert">
<div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
Your email must be between 10 and 100 characters long and look like an e-mail address.
</div>
</div>
</md-input-container>
</div>
</md-card-content>
</md-card>
</section>
<h3>Some other data</h3>
<section>
</section>
</div>
</form>
</div>
</md-content>
</div>
具有功能的控制器,该控制器必须在各部分之间导航:
var eventDetailsController = function($scope, $http, __config){
$scope.stepChanging = function(event, currentIndex, newIndex)
{
var valid = true;
if(!$scope.eventForm.contacts.$valid)
{
//call some function which triggers contacts validation message
//tried this as suggested in one of SO posts, but it did not work out
$scope.eventForm.contacts.$setTouched();
valid = false;
}
if(!$scope.eventForm.title.$valid)
{
//call some function which triggers title validation message
valid = false;
}
//call some function which triggers all validation messages
return valid;
}
};
答案 0 :(得分:1)
使用$validate()
功能:
$scope.eventForm.contacts.$validate();
$scope.eventForm.title.$validate();
来自文档:
$验证();
运行每个已注册的验证器(第一个同步验证器,然后运行异步验证器)。如果有效性更改为无效,则模型将设置为
undefined
。如果有效性更改为有效,则会将模型设置为最后一个可用的有效$modelValue
,即最后解析的值或从范围设置的最后一个值。