I am currently developing a form widget where the form schema is fetched from an API and generated dynamically. The library I am using for this purpose (vue-form-generator) comes with built-in validators that are directly referenced within the library itself. Here is an example:
"schema": {
"fields": [{
"type": "input",
"inputType": "email",
"label": "E-mail",
"model": "email",
"placeholder": "Email",
"validator": "VueFormGenerator.validators.email",
"required": true
},{
"type": "submit"
}]
}
Below is a snippet of my code:
<template>
<div id="app" v-if="loaded">
<vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator>
</div>
</template>
<script>
/* eslint no-eval: 0 */
import Vue from 'vue'
import VueFormGenerator from 'vue-form-generator/dist/vfg-core.js'
import 'vue-form-generator/dist/vfg-core.css'
Vue.use(VueFormGenerator)
export default {
name: 'app',
data: function () {
return {
loaded: false,
model: null,
schema: null,
formOptions: null
}
},
created: function () {
return fetch('http://localhost:3000/forms')
.then((response) => response.json())
.then((json) => {
// evaluating the validator's name
json.schema.fields.map((field) => {
if (field.validator) {
field.validator = eval(field.validator)
}
return field
})
// assigning the schema and model
this.model = json.model
this.schema = json.schema
this.formOptions = json.formOptions
// indicating that the schema has been loaded
this.loaded = true
})
.catch((ex) => {
console.log('parsing failed', ex)
})
}
}
</script>
I attempted to use eval()
to dynamically evaluate the validator's name and convert it into an actual function. However, this resulted in the following error message:
parsing failed ReferenceError: VueFormGenerator is not defined
at eval (eval at <anonymous> (eval at <anonymous> (http://localhost:8080/app.js:797:1)), <anonymous>:1:1)
at eval (eval at <anonymous> (http://localhost:8080/app.js:797:1), <anonymous>:35:29)
at Array.map (native)
at eval (eval at <anonymous> (http://localhost:8080/app.js:797:1), <anonymous>:33:26)
at <anonymous>
Would it be advisable to create a local translation to map validator names to their corresponding functions, or is there another approach that can be taken?
Thank you!