AngularJS Tutorial – Validation 101: Prevent Invalid Submissions

Two ways to prevent data submit when error issues occur

  • Preventing-invalid-form-submission

If you are a visual learner take a look at the video below which covers the topics outlined in the post



In this AngularJS Tutorial we will see two techniques to prevent the data submission in case of error. Both can live together in the same form to create a more robust code.

The ng-submit way

In this case we want that Angular evaluates a condition and then decide if to call or not the function

In the code above you can see at line 4 that the ng-submit parameter is a function (submitForm) belonging to the eventCtl contoller (in this case we referece the controller with an alias because we are using the “Controller as” syntax). Instead, in the code below, at line 4 we change the expression by adding a boolean value (addEventForm.$valid) chained to the function with the && (AND) operator: this force Angular to call the function only if the first value is true. As you can guess the addEventForm.$valid property is true if there are NO validation issues otherwise is false.



Disabling the button

The ng-submit techniques works but can create a little confusion. Think about a user that fills the form generating some issues and then clicks the submit button: nothing happens because the form is not valid and there is no submission, but the user has clicked the button and he has no response to his action. What we are doing now is disabling the submit button if the form is not valid.

Take a look at the code below at line 13. There is a ng-disable directive that evaluates the addEventForm.$invalid property that is true when ther are errors in the form. The result is that the submit button is disabled in case of validation issues and the user is guided without misunderstandings towards the resolution of the problems of validation.



Subscribe to our newswletter to obtain an extra discount on the full price on the video tutorial

.


This post is taken from our complete course AngularJS for the Real World – Learn by creating a WebApp. Take a look and give us a feedback!

Categories

About the Author:

Viaggiatore seriale e aspirante fotografo, lavoro in ambito ICT da oltre 15 anni. Collaboro con Webyourmind sin da quando era ancora solo un'idea nella testa dei fondatori. Sono appassionato di nuove tecnologie e di tutto quello che il web offre.

0 Comments
0 Pings & Trackbacks

Leave a Reply

%d bloggers like this: