0

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?

user4676723
  • 134
  • 11
  • I dont have enough time to post a full answer but FWIW you can do `if(field !== undefined)` instead of using `typeof`. Also, Angular has [built-in form validation](https://docs.angularjs.org/guide/forms). While this doesn't answer your problem it does give you an alternative solution – Dan Mar 27 '15 at 11:38
  • Actually, don't use `if(field !=== undefined)` as `undefined` can be overwritten. Instead, use a helper library like [lodash](https://lodash.com/docs) - `_.isUndefined(field)` – Dan Mar 27 '15 at 11:40
  • I'm using a modified version of that code. It's great for live validation of fields but it does nothing to prevent form submission - when you click Submit, it calls the `submit` function anyway. – user4676723 Mar 27 '15 at 11:41
  • You can prevent that by using the `ng-submit` directive and checking the validity of the form in that directive like `ng-submit='form.$valid && form.submit()'`. See [here](http://stackoverflow.com/questions/16263158/angularjs-prevent-form-submission-when-input-validation-fails) for more info. – Dan Mar 27 '15 at 11:45

2 Answers2

0

Codeschool provide full tutorial about form validation, so watch it and do it. First button near to the will execute ng-submitt="SOMEmETHOD" in tag. Thru the name of the form get $valid property and use this condition to disabled button. also use out of box angular validation methods in form of clear and easy to use directives like ng-minlenght. For live http requests use watcher or assync

$scope.$watch('contact.email',function(newValue, oldValues){ if(newValue !== undefined){ $timeout(function(){ REQUEST.success(function(){ scope.reqs = 'this is it' }) },600); } });

Janko
  • 202
  • 2
  • 11
0

_.isEmpty required underscore.js

$scope.test = "Test";

angular.isUndefined($scope.test);           // false
angular.isUndefined($scope.test.newField);  // true
_.isEmpty($scope.test);                     // false

$scope.test = "";

angular.isUndefined($scope.test);           // false
_.isEmpty($scope.test);                     // true

$scope.myObject = {};

angular.isUndefined($scope.test);           // false
_.isEmpty($scope.myObject );                // true

But I see all correct in your code. If you initialize $scope.contact={} before function submit is called, the error shouldn't appear. So, or you call the function submit and after you initialize $scope.contact or in some point you overwrite the value and after you call the function.

robBerto
  • 196
  • 2
  • 14