Reputation: 137
I am trying to validate a glob expression using Is-Valid-Glob which accepts string and array. The value which needs to be validated is received from a text field. The problem is that if we pass an invalid glob expression it produces the wrong result as every input is received as a string. For example:- If user inputs [] (invalid glob) its gets assigned to model variable as string '[]' and validation is done on '[]' instead of [] value. Is there a way by which we convert the value from string variable to object variable (only the value should not get type) and do validation?
PS: I am using Angular 2.
Upvotes: 5
Views: 33234
Reputation: 484
You can use JSON.parse to convert from string to objects:
var x = require('is-valid-glob');
var y = '[]';//'foo/*.js' any user provided string
// this will check if the user has provided an array object if so it
//will do a json.parse to remove the '' and then verify the string for a glob.
x(y[1] !== '['?y:JSON.parse(y));
Upvotes: 6
Reputation: 1609
Try with eval it is used to convert string into equivalent object for an example,
var a="[]";
console.log(a);// this will print "[]" as a string.
console.log(eval(a));// this will print an array object. With 0 length array object.
Upvotes: 3