AngularJS validation referencing form object with variable name


Let’s say I have a simple form with some Angular validation:

<form name="myForm">
    <input name="{{myField}}" 
            required />
    <div class="text-danger" ng-show="myForm[myField].$invalid">
        <div ng-show="myForm[myField].$error.required">
            Field is required.

Now let’s say I want to use a variable for the form name instead of a hard-coded string:

<form name="{{formName}}">

How can I modify myForm[myField].$invalid and myForm[myField].$error.required to still reference my form?


As of the current angular, you cannot have dynamically named form input elements. If you are doing this over a collection of forms, you can use the ng-form directive and do something like this (in jade syntax):

div(ng-repeat = "user in users", class="form-group")
      input(type="text", required, ng-model="", name="email")
      p(class="help-block" ng-show="$invalid">Valid Email Address required

Answered By – reptilicus

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.