I'm trying to do some basic form validation in Angular. I have the following code for my form:
<div class="col-xs-12 col-md-6" ng-controller="contactFormCtrl">
<form class="contact-form" ng-show="formVisible" novalidate>
<div class="form-group">
<label for="name">Name</label><small> Required</small>
<input type="text" class="form-control" ng-model="contact.name" id="name" placeholder="Name" required>
<div ng-show="nameEmpty">Please enter your name</div>
</div>
<div class="form-group">
<label for="email">E-mail</label><small> Required</small>
<input type="email" class="form-control" ng-model="contact.email" id="email" placeholder="E-mail" required>
<div ng-show="emailEmpty">Please enter your e-mail address</div>
</div>
<div class="form-group">
<label for="tel">Telephone</label>
<input type="text" class="form-control" ng-model="contact.tel" id="tel" placeholder="Telephone">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="5" ng-model="contact.message" required></textarea>
</div>
<input type="submit" ng-click="submit(contact)" class="btn btn-success" value="Submit">
<input type="button" ng-click="reset()" class="btn btn-primary" value="Reset">
</form>
<div ng-show="submissionSuccess">
<h4>Your message was sent successfully! We'll get back to you as soon as possible</h4>
<button class="btn btn-info" ng-click="reset()">Send another message</button>
</div>
</div>
And the following code in my controller:
$scope.contact = {};
$scope.formVisible = true;
$scope.userEmpty = false;
$scope.emailEmpty = false;
$scope.submit = function(contact) {
if (typeof $scope.contact.name != 'undefined' && typeof $scope.contact.email != 'undefined'){
$http.post('php/contact.php', contact)
.success(function(){
$scope.submissionSuccess = true
$scope.formVisible = false
})
} else if (!$scope.contact.name) {
$scope.nameEmpty = true
} else if (!$scope.contact.email) {
$scope.emailEmpty = true
}
}
The form already highlights empty or erroneously formatted fields in red, but now I'm trying to prevent submission of an invalid form too. My thought was to check if the $scope.contact.user
and $scope.contact.email
variables were undefined, and go from there. However, when I run this and try and submit and empty form, I get an error:
TypeError: Cannot read property 'name' of undefined
However, if I enter something in the Name field, then submit with an empty e-mail, it works as expected. This leads to think it's an initialization problem, but I thought I'd initialized the variable in the first line of my controller with $scope.contact = {}
.
What am I doing wrong?