I have a scenario where HTML is being dynamically generated from JSON, and I am looking to incorporate validation logic into the process.
For better understanding, here is an example snippet:
<div ng-switch on="field.type" ng-hide="{{ field.hide }}">
<div ng-switch-when="input" class= "col-md-6" ng-class="{'has-error': reqField(field.name, entity[field.name]) }">
<input
ng-model="entity[field.name]" id="{{field.name}}" class="form-control"
type="text" ng-style="setStyle(field.style)" ng-change="{{field.change}}" />
</div>
</div>
{
"title": "Json Title",
"id": "j_id",
"groupfields": [
{
"name": "jsonname",
"title": "JSON Title",
"type": "jsonselect",
"namevalue": "jsonvalue",
"combo": "jsondropdown",
"change" : "jsonChanged()"
},
{
"name": "jsonEmail",
"title": "JSON Email Address",
"type": "display"
},
{
"name": "jsonPhone",
"title": "JSON Phone Number",
"type": "display"
}
]
}, {
"title": "Json Title",
"id": "j_id",
"groupfields": [
{
"name": "jsonname",
"title": "JSON Title",
"type": "jsonselect",
"namevalue": "jsonvalue",
"combo": "jsondropdown",
"change" : "jsonChanged()"
},
{
"name": "jsonEmail",
"title": "JSON Email Address",
"type": "display"
},
{
"name": "jsonPhone",
"title": "JSON Phone Number",
"type": "display"
}
]
},
if (entityName) {
return false;
} else {
return true;
}
To provide clarity, for instance: 'field.type' within the ng-switch refers to the "type" in the JSON - enabling us to display specific HTML div based on various JSON keys/values relationships.
This suggests that a single HTML div could potentially generate multiple input fields, requiring dynamic handling.
My goal is to introduce validation when a required field is left empty. Currently, I attempted implementing ng-class="{has-error': }
which calls my function reqField. However, due to this function being executed for EVERY field with "type": jsonselect, it inefficiently checks if the field is empty, causing speed and usability issues (significant lag).
The JavaScript mentioned above essentially reflects the logic of the function reqField()
as it verifies the emptiness of the field (inefficient given the volume).
My aim is to instead utilize something like ng-required={{field.required}}
, incorporating a new key/value in the JSON dictating whether the field should be mandatory, such as:
{
"title": "Json Title",
"id": "j_id",
"groupfields": [
{
"name": "jsonname",
"title": "JSON Title",
"type": "jsonselect",
"namevalue": "jsonvalue",
"combo": "jsondropdown",
"change" : "jsonChanged()"
},
{
"name": "jsonEmail",
"title": "JSON Email Address",
"type": "display",
"required": true
},
{
"name": "jsonPhone",
"title": "JSON Phone Number",
"type": "display",
"required": true
}
]
},
~ and somehow transmit this data to the ng-class="{has-error': }
so that we can take action, like highlighting or any preferred response, once we ascertain if the field has been filled in or not.