为了账号安全,请及时绑定邮箱和手机立即绑定

Javascript 验证 - 检查字符串是否是正确的对象

Javascript 验证 - 检查字符串是否是正确的对象

繁星淼淼 2021-09-04 15:05:03
我有一个文本区域,我需要在其中放置一个对象[{  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  }}]我将此字符串保存在 mysql db 中,然后使用 php (laravel) 在 javascript 对象中打印它@if(!empty($useridobj))try {    useridobj = {!! $useridobj !!};    if(typeof useridobj != 'object'){        useridobj = '';    }} catch(err) {    useridobj = ''}@endif如果我在这个 textarea 中放置了一个正确的 obj 一切正常。但如果我像那样做错了[{name:'digitrust',para]控制台返回错误。所以我想首先在 javascript (angular.js) 中验证该字段。我尝试这样的事情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;}它不起作用。有人可以帮助我吗?
查看完整描述

1 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

也许您应该在服务器端进行验证,eval或者Function在上面的示例中存在一些安全问题,请参阅此。在这里,您有一种可能的方法,但是可以Function执行任何操作:


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>


查看完整回答
反对 回复 2021-09-04
  • 1 回答
  • 0 关注
  • 240 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信