How to validate dynamic form fields in AngularJS

Loading

In AngularJS, forms are a fundamental part of building interactive web applications. Dynamic forms, where the fields are created or modified based on user input or other variables, require validation to ensure that the data entered by the user is correct and meets the required criteria. AngularJS provides a built-in mechanism for form validation, and it is very flexible, making it suitable for dynamic forms.

In this guide, we will explain how to validate dynamic form fields in AngularJS, step by step. We will cover form creation, validation techniques, and how to handle dynamic form fields effectively.


1. Setting Up Your AngularJS Application

Before diving into dynamic form field validation, you need to set up your AngularJS application. This includes including AngularJS in your project and configuring a basic controller.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="FormController">

<!-- Dynamic Form will be generated here -->

</body>
</html>

Now, in your app.js file, create an AngularJS module and controller:

angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.formData = {};

// Define fields dynamically
$scope.fields = [
{ name: 'firstName', label: 'First Name', type: 'text', required: true },
{ name: 'lastName', label: 'Last Name', type: 'text', required: true },
{ name: 'email', label: 'Email', type: 'email', required: true },
{ name: 'phone', label: 'Phone', type: 'tel', required: false }
];

// A function to check if the form is valid
$scope.isFormValid = function() {
return $scope.myForm.$valid;
};

// A function to submit form data
$scope.submitForm = function() {
if ($scope.myForm.$valid) {
alert('Form submitted successfully!');
} else {
alert('Form is invalid.');
}
};
});

In this setup, we’ve defined a list of fields that can be dynamically added to the form. These fields include various input types such as text, email, and phone. We’ll loop over these fields in the HTML to generate dynamic form fields.


2. Generating the Dynamic Form in HTML

Now we need to loop over the fields array and generate corresponding form fields dynamically in the HTML.

<div>
<form name="myForm" ng-submit="submitForm()" novalidate>

<div ng-repeat="field in fields">
<label for="{{field.name}}">{{field.label}}:</label>

<input
type="{{field.type}}"
name="{{field.name}}"
ng-model="formData[field.name]"
ng-required="field.required"
ng-pattern="field.pattern"
class="form-control"
/>

<span class="error" ng-show="myForm[field.name].$error.required && myForm[field.name].$dirty">This field is required.</span>
<span class="error" ng-show="myForm[field.name].$error.email && myForm[field.name].$dirty">Please enter a valid email address.</span>
<span class="error" ng-show="myForm[field.name].$error.pattern && myForm[field.name].$dirty">Invalid format.</span>
</div>

<button type="submit" ng-disabled="!isFormValid()">Submit</button>
</form>
</div>

Here:

  • We use ng-repeat to loop over the fields array, generating a form input for each field.
  • The ng-model directive binds the input fields to the formData object.
  • We use AngularJS form validation properties ($valid, $dirty, $error) to check the validity of the fields.
  • We display error messages dynamically based on the form state.

3. Form Validation Basics

In AngularJS, there are several built-in validation rules that can be used for form fields:

  • Required: Ensures that the field is not empty.
  • Email: Ensures the entered value is a valid email address.
  • Pattern: Validates the input based on a regular expression.
  • Minlength/Maxlength: Limits the number of characters allowed.

These validations can be applied to any input field in the dynamic form.


4. Adding More Complex Validations

Sometimes, you need to apply more complex validation rules, such as conditional validation, custom validations, or cross-field validation (e.g., matching passwords). Here’s how you can handle these scenarios:

Conditional Validation

You can conditionally apply validation rules using AngularJS ng-if, ng-show, or ng-hide directives.

Example: Making the phone field required if the user selects a certain checkbox:

<input type="checkbox" ng-model="isPhoneRequired"> Add Phone Number

<div ng-if="isPhoneRequired">
<label for="phone">Phone:</label>
<input
type="tel"
name="phone"
ng-model="formData.phone"
ng-required="isPhoneRequired"
class="form-control"
/>
<span class="error" ng-show="myForm.phone.$error.required && myForm.phone.$dirty">Phone number is required.</span>
</div>

Here, the phone field becomes required only if the isPhoneRequired checkbox is checked.

Custom Validation

You can create custom validation rules in AngularJS using the ng-pattern directive or by defining custom validators.

angular.module('myApp')
.directive('validPhone', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.$validators.validPhone = function(modelValue, viewValue) {
// Custom validation logic for phone number
const phonePattern = /^[0-9]{10}$/;
return phonePattern.test(viewValue);
};
}
};
});
<input 
type="tel"
name="phone"
ng-model="formData.phone"
valid-phone
class="form-control"
/>
<span class="error" ng-show="myForm.phone.$error.validPhone">Please enter a valid phone number.</span>

This directive checks if the phone number matches a custom pattern and adds a validation error if it doesn’t.


5. Handling Dynamic Field Additions and Removals

In some cases, dynamic forms may allow users to add or remove fields. For example, you might allow the user to add multiple phone numbers. AngularJS makes this easy using ng-repeat.

<div ng-repeat="phone in formData.phones">
<label for="phone{{ $index }}">Phone {{ $index + 1 }}:</label>
<input type="tel" name="phone{{ $index }}" ng-model="formData.phones[$index]" ng-required="true" />
</div>

<button ng-click="addPhone()">Add Another Phone</button>
<button ng-click="removePhone()">Remove Last Phone</button>

In your controller:

jsCopyEdit$scope.formData = {
  phones: []
};

$scope.addPhone = function() {
  $scope.formData.phones.push('');
};

$scope.removePhone = function() {
  $scope.formData.phones.pop();
};

Here, the user can dynamically add or remove phone fields. AngularJS will keep track of each field’s validity, and the validation will adjust accordingly.


6. Showing Validation Messages

AngularJS makes it easy to show validation messages when a field is invalid. You can show specific error messages depending on the form state using ng-show or ng-if. Some common validation messages include:

<span class="error" ng-show="myForm[field.name].$error.required && myForm[field.name].$dirty">
This field is required.
</span>
<span class="error" ng-show="myForm[field.name].$error.email && myForm[field.name].$dirty">
Please enter a valid email.
</span>

This ensures that the user gets immediate feedback about their input.

Leave a Reply

Your email address will not be published. Required fields are marked *