Jack Johnson
Jack Johnson

Reputation: 1535

AngularJS - perform extra validation on form submit

I've been googling for a while and can't seem to find a good answer for my specific case. I've found ways to do real-time validations but I want to combine that with some custom validations after a user clicks on "submit". I want to allow the user to still click on the submit even if it's not valid but then I'll cancel the submission in the code. Take the following code:

<form name="cashForm" id="cashForm" novalidate>
  <input type="text" id="name" required /> //
  <input type="number" placeholder="Tax: " required name="tax" id="tax" />
  <input type="number" placeholder="Tip: " required name="tip" id="tip" />
  <button ng-click="submission()" ng-disabled="paymentForm.$invalid">Submit</button>
</form>


//inside controller
this.submission = function() {
  //check if tip + tax is over 20
  //prevent form and show error message if not
  //otherwise allow default behavior
}

So I only want the form to actually submit if the tax/tip is over 10. How do I check for this and how do I prevent the form submission if it doesn't meet the requirements? Also, would I put this logic in the controller?

Upvotes: 0

Views: 138

Answers (1)

Matthew Cawley
Matthew Cawley

Reputation: 2818

It looks pretty close to what you're after to me. Just a couple of things...

Add ng-model directives to your input controls to create two-way data-bindings that you can pick up and use in your controller:

<form name="cashForm" id="cashForm" novalidate>
    <input id="name" name="name" type="text" ng-model="nameValue" required />
    <input id="tax" name="tax" type="number" ng-model="taxValue" placeholder="Tax: " required   />
    <input id="tip" name="tip" type="number" ng-model="tipValue" placeholder="Tip: " required />
    <button 
        ng-click="submission()" 
        ng-disabled="paymentForm.$invalid"> 
        Submit 
    </button>

Inject $scope into your controller to allow you to pick up those ng-model bindings in your controller's submission method:

function submission() {

    $scope.errorMsg = "";

    if ($scope.taxValue <= 10) {
        $scope.errorMsg = "tax not greater than 10";
        return;
    }

    if ($scope.tipValue <= 10) {
        $scope.errorMsg = "tip not greater than 10";
        return;
    }

    // If you reached here your post-click validation passed, 
    // so continue to submit the data...

 }

You could then display an error message using the ng-if directive with a css class that highlights the error message:

<div ng-if="!!errorMessage" class="text-danger">
    {{ errorMessage }}
</div>

Finally, once you've cracked using $scope in your controller you might want to read about the perceived evils of using $scope and consider switching to controller-as syntax instead. Check out John Papa's Blog Post AngularJS's Controller As and the vm Variable

Upvotes: 1

Related Questions