20 Jan 2015, 04:00

AngularJS: Form Validation

A common scenario when validating form input is to call back to the server to check some detail or other before the final submission. For example, where the user has been asked to select a username, we might choose to verify that the username is available ahead of time.

Rather than creating scope variables to keep track of whether or not a form is valid, we are better off using the built-in validation facility that AngularJS provides out of the box!

One powerful feature is the ability to set custom error conditions on a form field (in additon to minlength, required etc.). The following code snippets provide an example of how this can be used:

HTML

<form name="form" novalidate ng-submit="ConfirmAccount()">
	<p ng-show="form.$dirty && form.username.$error.conflict">
		Username is not available. Please try another one.
	</p>
	<input type="text" ng-focus="form.$setPristine()" name="username" ng-model="confirm.username">
</form>

form.username.$error.conflict will exist and be set to true by our controller once the username check has been performed.

Javascript

$scope.ConfirmAccount = function() {
	checkUserAvailable(user.username).then(function(result) {
		$scope.form.username.$setValidity("conflict", result.usernameAvailable);
		if( $scope.form.$invalid ) { return; }

		// proceed with form logic
	}
};

If the server returns result.usernameAvailable == false then the validity of form.username will be false, and our error message will be displayed. The "conflict" key is an aribtary label that I’ve chosen to indicate when the username is already taken, but you can choose anything you like.