0

I have a textarea where I need to put an object like that

[{
  name: 'digitrust',
  params: {
    init: {
      member: 'example_member_id',
      site: 'example_site_id'
    },
    callback: function(digiTrustResult) {
      if (digiTrustResult.success) {
        var el = document.getElementById('dtidOutput');
        console.log('Success', digiTrustResult.identity)
      } else {
        console.error('Digitrust init failed')
      }
    }
  },
  storage: {
    type: 'html5',
    name: 'pbjsdigitrust',
    expires: 60
  }
}]

I save this string in a mysql db and after I print it in a javascript object with php (laravel)

@if(!empty($useridobj))
try {
    useridobj = {!! $useridobj !!};
    if(typeof useridobj != 'object'){
        useridobj = '';
    }
} catch(err) {
    useridobj = ''
}
@endif

If I put a correct obj in this textarea all works fine. But if I put something wrong like that

[{name:'digitrust',para]

console return an error.

So I'd like to validate the field first, in javascript (angular.js). I try something like that

if(!eval("var this_useridobj = "+ this.form.get("useridobj").value)){
  this.form.get("useridobj").setErrors({ server: "UserId Object is not an object!" });
  console.warn(this.form.get("useridobj"));
  return false;
}

It doesn't work. Someone can help me please?

Thank u

Kormi Web Solutions
  • 533
  • 1
  • 4
  • 18

1 Answers1

1

Maybe you should validate in server side, eval or Function in the example above have some security issues, see this. Here you have a possible approach, but that Function executes anything:

document.getElementById("validate").addEventListener("click",()=>{
const json = document.getElementById("json").value;
const valid = (()=>{
    try {
      return (typeof (Function("return "+json))() === 'object')?true:false;
    }
    catch(error) {
      return false;
}})();

console.log(valid)
});

//Try alert("something") in the textarea
<textarea id="json">{prop:[1,2,3}</textarea>
<button id="validate">
validate
</button>
Emeeus
  • 5,072
  • 2
  • 25
  • 37