AngularJS Forms: Validating User Input

AngularJS provides several built-in directives and features for validating user input in forms. Here are some ways to validate user input in AngularJS forms:

1. Using ng-model and ng-required directives: You can use the ng-model directive to bind form inputs to a model variable and the ng-required directive to specify whether a field is required or not. For example:

<code>html
&lt;form name=&quot;myForm&quot;&gt;
&lt;input type=&quot;text&quot; ng-model=&quot;name&quot; ng-required=&quot;true&quot;&gt;
&lt;span ng-show=&quot;myForm.name.$error.required&quot;&gt;Name is required.&lt;/span&gt;
&lt;/form&gt;
</code>

2. Using ng-pattern directive: You can use the ng-pattern directive to specify a regular expression pattern that the input value must match. For example, to validate an email address:

<code>html
&lt;form name=&quot;myForm&quot;&gt;
&lt;input type=&quot;email&quot; ng-model=&quot;email&quot; ng-pattern=&quot;/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/&quot;&gt;
&lt;span ng-show=&quot;myForm.email.$error.pattern&quot;&gt;Invalid email address.&lt;/span&gt;
&lt;/form&gt;
</code>

3. Using ng-minlength and ng-maxlength directives: You can use the ng-minlength and ng-maxlength directives to specify the minimum and maximum length of an input value. For example:

<code>html
&lt;form name=&quot;myForm&quot;&gt;
&lt;input type=&quot;text&quot; ng-model=&quot;password&quot; ng-minlength=&quot;6&quot; ng-maxlength=&quot;10&quot;&gt;
&lt;span ng-show=&quot;myForm.password.$error.minlength&quot;&gt;Password is too short.&lt;/span&gt;
&lt;span ng-show=&quot;myForm.password.$error.maxlength&quot;&gt;Password is too long.&lt;/span&gt;
&lt;/form&gt;
</code>

4. Using custom validation directives: You can create custom validation directives to implement complex validation logic. For example, you can create a directive to validate that two password fields match:

<code>html
&lt;form name=&quot;myForm&quot;&gt;
&lt;input type=&quot;password&quot; ng-model=&quot;password1&quot;&gt;
&lt;input type=&quot;password&quot; ng-model=&quot;password2&quot; match-password=&quot;password1&quot;&gt;
&lt;span ng-show=&quot;myForm.password2.$error.matchPassword&quot;&gt;Passwords do not match.&lt;/span&gt;
&lt;/form&gt;
</code>

<code>javascript
app.directive(‘matchPassword’, function() {
return {
require: ‘ngModel’,
link: function(scope, element, attrs, ctrl) {
ctrl.$validators.matchPassword = function(modelValue, viewValue) {
var password = scope.$eval(attrs.matchPassword);
return viewValue === password;
};
}
};
});
</code>

These are just a few examples of how you can validate user input in AngularJS forms. AngularJS provides many more built-in directives and features for form validation, such as ng-min, ng-max, ng-pattern, etc. You can also create custom validation directives to implement your own validation logic.

Scroll to Top