0

I have an angular form. I am trying to implement some validation on required fields, like in this nice tutorial, which says that angular has this functionality "built in". However- it isn't working for me. When I submit the form without having filled out the fields, nothing happens. Can anyone see why?

    <form id = "myForm" name="myForm" novalidate>

                        <div class="form-group" ng-class="{ 'has-error' : myForm.name.$invalid && !myForm.name.$pristine && submitted }">
                        <input type="text" name="name" class="form-control" ng-model="company.name" required>
                        <p ng-show="myForm.name.$invalid && !myForm.name.$pristine" >Your firm's name is required.</p>
                        </div>
                        <br />
                        <br />
                        <div class="form-group" ng-class="{ 'has-error' : myForm.address.$invalid && !myForm.address.$pristine && submitted }">
                        <input type="text" class="form-control" id = "address" name="address"  ng-model="company.address" required>
                         <p ng-show="myForm.address.$invalid && !myForm.address.$pristine" class="help-block">Your address is required.</p>
                        </div>

<button type="submit" ng-click= "createAccount()" class="btn btn-small btn-primary">GO

    </button>

        </form>

I have also included $scope.submitted = true; in my createAccount() function.

bookthief
  • 2,443
  • 8
  • 41
  • 54
  • 1
    This may help you http://stackoverflow.com/questions/18798375/show-validation-error-messages-on-submit-in-angularjs – Chandermani Feb 25 '14 at 15:44
  • @Chandermani this is similar to what I have attempted above- I have set the submitted property to true in the function in the controller. – bookthief Feb 25 '14 at 15:53

1 Answers1

2

Remember that AngularJS is a client side framework. Your validation must be performed before you submit something.

Add ng-disabled to your submit button:

<button type="submit" ng-disabled="myForm.$invalid" ng-click= "createAccount()" class="btn btn-small btn-primary">GO</button>

Or check the validation status in the createAccount() function like in the tutorial example you are referring to:

if (!$scope.myForm.$valid) {
   alert('Something is wrong');
}
Lars Behnke
  • 1,901
  • 2
  • 14
  • 14
  • Thanks, that's one way of handling the validation- but in the tutorial, it shows it is possible to submit the form first and then have all the required fields highlighted with the error messages. – bookthief Feb 25 '14 at 15:52
  • 1
    Ok, I think I grasped what you want. Besides the link @Chandermani posted, check also out http://stackoverflow.com/questions/17452247/validate-form-field-only-on-submit-or-user-input – Lars Behnke Feb 25 '14 at 16:33