我刚刚发现了Angular和Material设计,我真的很喜欢开箱即用的所有功能。我创建了一个带验证的联系表单,当需要字段或格式不正确时,它会给出错误消息。唯一缺少的是当用户点击"提交"按钮,他们仍然可以将表单发送到服务器。所以错误信息确实没有帮助。
HTML :
<md-content layout-padding="">
<form name="projectForm" action="/" method="post" novalidate>
<div layout-gt-sm="row">
<md-input-container class="md-block" flex-gt-sm="">
<label>Email</label>
<input required="" type="email" name="emailAddress" ng-model="project.emailAddress" ng-pattern="/^.+@.+\..+$/">
<div ng-messages="projectForm.emailAddress.$error" role="alert">
<div ng-message-exp="['required', 'pattern']">
Your email must be in correct format and look like an email address.
</div>
</div>
</md-input-container>
</div>
<md-input-container class="md-block">
<label>Message</label>
<textarea required="" name="content" md-maxlength="50" ng-model="project.content" rows="3" md-select-on-focus=""></textarea>
<div ng-messages="projectForm.content.$error" role="alert">
<div ng-message="required">
Your must enter a message.
</div>
</div>
</md-input-container>
<md-button type="submit" class="submit">Submit</md-button>
JS :
angular
.module('toast', ['ngMaterial', 'ngMessages'])
.controller('formCtrl', function($scope) {
$scope.project = {
//scope stuff goes here
};
})
这是Codepen。
答案 0 :(得分:3)
表单无效时禁用提交按钮:
<md-button type="submit" class="submit" ng-disabled="projectForm.$invalid">Submit</md-button>
答案 1 :(得分:1)
这个你可以试试
对于最新的角度,您可以使用下面的简单代码在类型脚本中验证您的表单
假设你的表单是这样的
<form [formGroup]="userForm" novalidate (ngSubmit)="onSubmit()">
你可以像这样验证它的状态
if (!this.userForm.valid) {
return;
}