Flying memes

Angular.js prevent an invalid form submission

Angular.js does an excellent job on preventing a form submission when invalid but only if the action attribute is not present, otherwise we have to implement a few tricks to achieve the same behaviour.

<div ng-app>
    <form action="#" novalidate name="register" ng-submit="(submitted=true) && register.$invalid && $event.preventDefault()" ng-class="{true:'submitted'}[submitted]">
        <input type="text" ng-model="user.username" required> 
        <input type="email" ng-model="">
        <input type="submit">

We used $event.preventDefault() to stop the submit propagation only if the form is invalid; plus we set a $scope variable ‘submitted’ to true in order to have a class that gets appended to the form if the form has been submitted in an invalid state at least once, even if none of its fields have been ‘touched’ – so it’s still ng-pristine.

Here’s the demo on jsFiddle:

Tags: ,