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="user.email">
        <input type="submit">
    </form>
</div>

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: http://jsfiddle.net/sandro_paganotti/8Sdxk/2/

Tags: ,