Basic form validation with angular

First

Basic angular form validation is done declaritve on the form elements. But therefore the form must have a name so it can be used in the input elements. You allso have to set the novalidate keyword on the form element to preven html5 to validate the form. We don't want html5 to do that because we are going to implement our own. The form will look like this:

<form ng-submit="submit()" name="opmerkingenForm"  novalidate  >
</form>

So we have a submit function in our scope, the html5 validate function is disabled and the form has a name so it can be used in other elements. Now we add a input element to validate:

<input type="text" placeholder="Name" name="naam" class="form-control" style="width:100%;" ng-model="formData.Naam" required/>

We put just the required directive. Next to this directive angular provides you with the following validation directives:

Valiation directives

  • pattern
  • min-length
  • max-length
  • min
  • max

Validation messages

For showing validation messages we have to add some elements.

<div class="error-container" ng-show="opmerkingenForm.naam.$invalid && opmerkingenForm.submitted">
		<small class="error" ng-show="opmerkingenForm.naam.$error.required">
			Naam is verplicht!
		<small>	
</div>

The div with the messages is going to be visible if the form is submitted and the state of the 'naam' elment is invalid. More on showin and hiding elements. We have the following states on avaiable on our elements:

Element states:

  • $pristine, a boolean indicating is touched
  • $dirty, a boolean indicating the form is acually changed
  • $valid, a boolean indicating the form is valid
  • $valid, a boolean indicating the form is invalid
  • $error, an object with the errors

With the error state we are showing our error elements. The last thing we miss is the opmerkingForm.submitted boolean. Angular hasn't a property if the form is sumbitted, so we do that ourselfes, like this:

        if ($scope.opmerkingenForm.$valid) {
            // normal save function
        }
        else {
	    // set the submitted function for showing validation
            $scope.opmerkingenForm.submitted = true;
        }

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!