Explain Codes LogoExplain Codes Logo

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

javascript
angular-validation
dynamic-forms
ng-repeat
Anton ShumikhinbyAnton Shumikhin·Feb 22, 2025
TLDR

To validate dynamic inputs with ng-repeat, bind them to unique ng-model instances and use required or other validation directives. Each input's name is effectively expressed using name="{{'input' + $index}}", enabling ng-messages for immediate error feedback.

<form name="dynamicForm" novalidate> <div ng-form="subForm" ng-repeat="input in inputs" ng-show="input.show"> <input type="text" name="{{'input' + $index}}" ng-model="input.value" required /> <div ng-messages="subForm['input' + $index].$error"> <span ng-message="required">This field is required</span> <!-- Add other ng-messages here for different validations --> </div> </div> </form>

The name attribute is dynamically set with {{$index}} which ensures a unique validation context for each input spawned by ng-repeat. Using subForm['input' + $index].$error, each input control's errors can be individually processed, displaying instant and clear validation feedback to the end-user.

Mastering dynamic form and unique validation

By incorporating ng-form="subForm" inside the ng-repeat, AngularJS scopes each expanding input into a distinct sub-form providing granular validation control, ideal when dealing with dynamic form controls like tables or lists. Conditional display of error messages is achieved using ng-show or ng-if.

In addition, AngularJS provides lots of joy right out-of-the-box for error message processing. By binding to subForm.input.$dirty and !subForm.input.$valid, error messages are made reactive and dynamic, only appearing when truly necessary.

Advanced validation with custom directives

Need complex validation logic or wish to reuse existing checks? No worries! Opt for creating a custom directive. This gives you the flexibility for dynamic attribute renaming, extending validation logic, or asynchronous validations.

Need to run checks on specific patterns such as email validation or dates? ngPattern provides a solution which matches inputs against regular expressions. It's like a regex party in your HTML!

Let's talk updates: Ng-Change

As we dive in, ever admired a fluid UI that reacts spontaneously? AngularJS ng-change directive provides a solution by triggering validation dynamically at each input update.

Common pitfalls addressed

The most common issues usually are forgetting to add the name attribute for inputs, and neglecting to insert novalidate to bypass HTML5 native validation. Always hiking the extra mile to provide unique names for elements under ng-repeat will save you the hustle of debugging Angular's validation system.