我无法弄清楚我的表单验证错误。我正在使用ng-show,我认为我正确地引用了表单控件,尽管我以前从未这样做过(我是AngularJS的新手)。我已经在SO上关注了其他几个例子,但不知怎的,我仍然遗漏了一些东西。这是我的代码Plunker。在Plunker中,无论是否输入了字段,我的错误信息都会显示出来。出于某种原因,在localhost上运行代码,根本不会显示错误消息。
此外,以下是其中的一部分:
HTML :
<div class="form-group">
<label for="emailAddress">Email address (required):</label>
<input id="emailAddress" type="text" class="form-control" placeholder="Email address" ng-model="about.email" ng-pattern="about.emailFormat" required/>
<span ng-show="contactForm.emailAddress.$dirty && contactForm.emailAddress.$error.pattern">Email is invalid</span>
</div>
JS :
(function () {
angular
.module('app')
.controller('About', About);
function About() {
var vm = this;
vm.name = "";
vm.email = "";
vm.message = "";
vm.emailFormat = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,10}$/;
vm.sendMail = function () {
};
vm.cancel = function() {
vm.name = "";
vm.email = "";
vm.message = "";
};
return vm;
}})();
答案 0 :(得分:1)
假设您有一个名称属性为contactForm
的表单。您忘记了表单元素中的name属性。要访问您的input元素,它应该是formName.inputName
<强> HTML 强>:
<div class="form-group">
<label for="emailAddress">Email address (required):</label>
<input id="emailAddress"
name="emailAddress" type="text"
class="form-control"
placeholder="Email address"
ng-model="about.email"
ng-pattern="about.emailFormat"
required/>
<span ng-show="contactForm.emailAddress.$dirty && contactForm.emailAddress.$error.pattern">Email is invalid</span>
</div>
答案 1 :(得分:1)
每当您进行表单验证时,都需要使用正确的HTML标记,这就是为什么它不能按预期工作的原因。
<form role="form" name="contactForm">
<div class="form-group">
<label for="emailAddress">Email address (required):</label>
<input name="emailAddress" id="emailAddress" type="text" class="form-control" placeholder="Email address" ng-model="about.email" ng-pattern="about.emailFormat" required/>
<span ng-show="contactForm.emailAddress.$dirty && contactForm.emailAddress.$error.pattern">Email is invalid</span>
</div>
</form>