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.

2
  • 1
    This may help you stackoverflow.com/questions/18798375/… Commented Feb 25, 2014 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. Commented Feb 25, 2014 at 15:53

1 Answer 1

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');
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Ok, I think I grasped what you want. Besides the link @Chandermani posted, check also out stackoverflow.com/questions/17452247/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.