Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
* Custom submit directive that will only submit when all the validation has passed
* for all the fields. This extends on the ng-submit directive provided by AngularJS.
* This directive will also remove the 'pristine' flag from all the fields when
* hitting submit, allowing the form to display no errors until the submit button
* is clicked/enter is pressed.
* The variable 'app' is the instance of a module.
* E.g. var app = angular.module('my-app', []);
app.directive('customSubmit', function()
return {
restrict: 'A',
link: function( scope , element , attributes )
element.bind('submit', function(e) {
['input', 'textarea', 'select'].forEach(function(e){
// Get the form object.
var form = scope[ ];
// Set all the fields to dirty and apply the changes on the scope so that
// validation errors are shown on submit only.
angular.forEach( form , function ( formElement , fieldName ) {
// If the fieldname starts with a '$' sign, it means it's an Angular
// property or function. Skip those items.
if ( fieldName[0] === '$' ) return;
formElement.$pristine = false;
formElement.$dirty = true;
// Do not continue if the form is invalid.
if ( form.$invalid ) {
// Focus on the first field that is invalid.
return false;
// From this point and below, we can assume that the form is valid.
scope.$eval( attributes.customSubmit );
<!-- Add the custom submit attribute instead of the traditional ng-submit.
Input fields must have the 'name' attribute, that's how Angular knows
how to highlight the field that has an error.
When we want to display the 'required' error validation, we want to also check that the field
is not dirty, which means that when the page loads, the errors will not appear.
<form name="createProjectForm" data-custom-submit="submit(project)" novalidate>
<label for="name">Name:</label>
<input type="text" name="name" id="name" placeholder="Project name" required data-ng-minlength="3" data-ng-model="">
<span class="help-inline" ng-show="$dirty &&$error.required">The name field is required.</span>
<span class="help-inline" ng-show="$error.minlength">The name must be at least 3 characters.</span>
<button type="submit">Create project</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment