5

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.

3
  • 1
    please consider reading the asking help to ask a valid and quality post Commented Dec 26, 2017 at 6:13
  • share example with us Commented Dec 26, 2017 at 6:39
  • Have you tried using eval? Commented Dec 26, 2017 at 6:45

3 Answers 3

6

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Vikramjit, I am using the similar hack serves the purpose. Looking for a more satisfiable solution. Also, need to add cases for {} (invalid glob), it will pass in this scenario
3

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.

1 Comment

thanks, @deepak, eval will not be helpful in case of strings. eg "foo/*.js" (valid glob).
-2

We can use Object.assign({},object) to convert string into object.

1 Comment

Doesn't work. In case of a string, it splits the string to an array where each element is a single character from that string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.