Reputation: 1891
I'm having trouble with figuring out what I'm doing wrong with my form validation. I'm using the ng-show, and I think I'm referencing the form controls correctly, although I've never done this before (I'm new to AngularJS). I've followed several other examples here on SO, but somehow I'm still missing something. Here is a Plunker of my code. In the Plunker, my error messages show up regardless of whether the fields have been entered. For some reason, running the code on localhost, the error messages don't show up at all.
Additionally, here is a portion of it:
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;
}})();
Upvotes: 1
Views: 1193
Reputation: 2753
Whenever you do form validation, you need to make use of the proper HTML tags, thus that's why it's not working as expected.
<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>
Upvotes: 1
Reputation: 6620
Assuming you have a form with name attribute contactForm
.You forgot the name attribute from form element.To access your input element, it should be 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>
Working Fiddle: https://plnkr.co/edit/LIFcg3dRogw5yYgeuUac?p=preview
For more Info : https://scotch.io/tutorials/angularjs-form-validation
Upvotes: 1