-1

I am writing a code for a simple client-side form validation. I am trying to create object with properties & values used in a process of validation (for each separate input) and then attach them to the input nodes.

I am trying to find a way to pair these objects automatically to respective inputs. In the code below, I found a way to do this, but for a price to use eval() function, which I would rather avoid. Is there an other way to do this in JS?

<label class="c-contact-form__label" for="your_name">Your Name *</label>
<input class="" type="text" name="your_name" maxlength="50" size="30">    

var your_name = {
  regex: /^([a-z\u00C0-\u02AB,.'´`]{1,}\.?\s?)([a-z\u00C0-\u02AB,.'´`]?\.?\s?)+$/i,
  required: true,
  invalid: "Your name seems a little bit weird…",
  empty: "Please, fill in your name."
};

// From within a function of eventListener:

var Merged = Object.assign(this, eval(this.name)); // Use of eval()
console.log(Merged.invalid); // "Your name seems a little bit weird…",

I was googling for a solution quite hard, and I've read the possible context[varName] solution, but it doesn't seem to work (or I dont't get it).

HynekS
  • 2,738
  • 1
  • 19
  • 34
  • Possible duplicate of [Convert string to variable name in JavaScript](https://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript) – CBroe Jan 15 '18 at 12:59

2 Answers2

0

You can use eval() or context[varName]. Context can be a variable with var, const or let or directly window[varName] if you need it to be global.

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • Thank you. I have read similar questions here on SO, but I might not get the context[varName] solution. Either `this[name]` or `this['name']` returns `undefined` on the last line. – HynekS Jan 15 '18 at 13:17
0

The issue was that the original code was wrapped in IIFE. Therefore – AFAIK – it can not be accesed with bracket notation, because it does not exist in global scope, and the object itself does not have a parent.

const foo = (() => {
  let bar = 'obj';
  const obj = {
    // not accessible by [var]whatever. AFAIK
    whatever: 'bar',
  } 
  console.log([bar].whatever); // undefined
})();

I solve it by wraping an object into parent object:

const foo = (() => {
  let bar = 'obj';
  const parent = {
    //now accessible by parent[bar].
    obj: {
      whatever: 'bar',
    }
  }
  console.log(parent[bar].whatever); // bar
})();
HynekS
  • 2,738
  • 1
  • 19
  • 34