【问题标题】:How to do form validation with JS for a chrome extension?如何使用 JS 对 chrome 扩展进行表单验证?
【发布时间】:2015-08-13 06:24:03
【问题描述】:

Chrome 内容安全政策规定,

内联 JavaScript 不会被执行。此限制禁止两者 内联块和内联事件处理程序(例如<button onclick="...">)。

我想用 JS 验证输入。由于onsubmit,onclick或任何东西都不能使用,我该怎么做?我是 JS 和扩展开发的新手。欢迎任何帮助。

【问题讨论】:

  • 不要使用内联事件处理程序。使用addEventListener

标签: javascript html google-chrome-extension


【解决方案1】:

您可以使用addEventListener,例如像这样:

// Function to add event listener to table
var el = document.getElementById("targetElement");
el.addEventListener("click", function() { alert('Hoorey!'); }, false);

这是一个单独的 .js 文件。

【讨论】:

  • 正如我所说,我对 JS 还很陌生。如果你能分享任何 tuts 来理解addEventListener 的概念,那将会非常有帮助。如果它在谷歌搜索中很容易获得,我可以尝试:)
  • 当然!这是将事件侦听器附加到任何 DOM 元素的标准 JavaScript 方法。这真的很有帮助来源:developer.mozilla.org/en-US/docs/Web/API/EventTarget/…
  • 非常感谢。这很有帮助:)
【解决方案2】:

考虑到您希望确保多个输入有效,然后让用户提交表单,这是我使用 jquery 的解决方案:

// selectors
var input1 = $(#input1ID); // name
var input2 = $(#input2ID); // phone

// regular expressions
var regexp_input1 = /^[a-zA-Z]$/; 
var regexp_input2 = /^([0-9]$/;

// map object
var your_form_map  = {
// map variables
 input1 : false, // if it is required 
 input2 : true // if it is not required but you dont want the user input incorrect characters. 
}

var invalid_color = "red";
var valid_color = "green";
function validForm (selector, regexp_variable, map_obj , map_var) {
    selector.on('change keyup anyotherevent addwithspace',function(){ // CHANGE validates input with auto complete which you can hardly disable it with chrome. 
        if (regexp_variable.test($(this).val()) == false || $(this).val().trim().length === 0) {
            $(this).css("color" : invalid_color);
            map_obj[map_var] = false;
            return false;
        } else {
            $(this).css("color" : text_valid);
            map_obj[map_var] = true;
            return true;
        }
    });
}

现在让我们调用验证器函数:

validForm(input1, regexp_input1, your_form_map, "input1"); // second input1 is your map's object variable NOT your input selector.  

提交验证表格的时间:

$('your_submit_btn_ID').on('click anyOtherEvent', function() {
   var temp = true;
   for (var key in your_form_map) { // looping through your map object and make sure all inputs are true. 
       if (!your_form_map[key]) {
           alert(key + "is invalid");
           return false;
       }
   }
   // submit your form here ...
   $.ajax({...});
   // have fun here... 
});

【讨论】:

  • 我不擅长 JQuery。现在刚开始用JS。将来我一定会继续关注这一点。 :) 非常感谢。
猜你喜欢
  • 2011-11-20
  • 2016-09-26
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 2021-01-18
  • 2022-09-29
相关资源
最近更新 更多