the overengineer

Prevent form validation on ng-click in AngularJS

• blog

With the following HTML, validation on your form will be triggered every time you click on either button:

<form ng-submit="updateTitle()">
    <input type="text" ng-model="title" required />        
    <button>Update</button>
    <button ng-click="alert('hi!')">Say hi</button>
</form>

But we don’t necessarily want that to happen for our “Say hi” button. So how do we stop it?

Well, according to the W3 specification on button elements, if you don’t specify a type="[something]" for your button, then it will default to type="submit":

In such a case, any click to this button, no matter what ng-click says, will submit the form. And submitting the form will trigger validation. The solution? Make sure it’s type isn’t submit:

<form ng-submit="updateTitle()">
    <input type="text" ng-model="title" required />        
    <button>Update</button>
    <button type="button" ng-click="alert('hi!')">Say hi</button>
</form>

The form is no longer submitted on click, and we merrily say “hi!” to our users without a validation care in the world.

Happy coding!

comments powered by Disqus