Dynamic binding of “ng-required” for Validation

I like to share the solution which I came across while working on dynamic validation of form in AngularJS.

 

Scenario:
Usually Angular JS form element look for the “required” attribute to perform validation functions.


For instance, only require field B –say custom entry, if the field A has certain value-if you selects Field name as “Custom” as a choice. Than, Ng-required allows you to set the required attribute depending on the Boolean test .


As an example, <input required> and <input ng-required=”true”> are essentially the same thing.

 

Code-snippet for ng-required (sample.html)

In the below snippet you can see I have used ng-required={{isRequired}} for <input type=”text” name=”txtcustom”

 

<form name=”testForm” ng-submit=”saveForm();” ng-controller=”testController”>
    <input name=”input” type=”text” id=”txtRuleName” ng-model=”ruleName” class=”form-control” required>
    <select ng-model="currentfieldList" ng-options="sinfo for sinfo in fieldList" id="selectFieldName" ng-change="onFieldChange()" class="form-control"></select>

    <input name=”input” type=”text” id=”txtDescr” ng-model=”description” class=”form-control” required>
    <input name=”input” type=”text” id=”txtCustom” ng-model=” customField” class=”form-control” ng-required={ {isRequired}}>
    <button type=”submit” class=”btn btn-success”>Save</button>
</form>

 

We can set Boolean value of ng-required using controller as below.

 

$scope.isRequired=false;
$scope.onFieldChange = function () {
            if ($scope.currentfieldList == "Custom") {
                $scope.isRequired = true;
            }
            else {
                $scope.isRequired = false;
            }
   }

 

After the code is ready,save the code and run you will see that you are not getting the expected result,but after debugging you can see “isRequired” value is set to true but still value is not applicable

 

So here one can stuck,question is if the value is set as “true” in HTML tag that why its not working?

 

Solution:

-Here I got the answer after using isRequired in curly braces(i.e {{isRequired}}) the value internally sets as string.

 

simple solution,just remove the curly braces of isRequired (i.e ng-Required=isRequired) it will work.

Write a comment
Cancel Reply
  • Wando November 4, 2020, 7:18 am
    This solved a Problem i was working on for way to long. Thank you very much.
    reply