gpt4 book ai didi

数据属性中的 Javascript 正则表达式

转载 作者:行者123 更新时间:2023-11-30 17:44:54 29 4
gpt4 key购买 nike

我正在制作自定义表单验证插件。它使用放置在每个需要满足特殊参数的输入中的 HTML5 数据属性。示例:

<input type="text" name="year" id="year" data-valid='{"message":"a", "regEx":"^\$?(\d+|\d*\.\d+)$"}' required />

初始数据对象进入 javascript 时很好,但是当我在某些自定义正则表达式下扩展对象时,扩展对象导致错误。

这是创建对象的代码片段:

var data = $this.data();           
var defaults = {
specialType: '', //currently accepts VIN, USPhone and Email
inputType: '', //intLetter(accepts only integers and numbers), integer, float, floatInteger(accepts both floats or integer) letters, or all(accepts anything the user types)
inputLength: '', //define max length user can input
regEx: '', //define ur own regular expression (this will override the datatype)
message: ''
}

var validObj = $.extend({}, defaults, data.valid);

现在,如果我使用不带\的正则表达式,它的工作方式类似于:^[0-9]+$

输入的 html 看起来像:

<input type="text" name="year" id="year" data-valid='{"message":"a", "regEx":"^[a-zA-Z]+$"}' required />

扩展的对象将在 google chrome 控制台中打印,如下所示:

Object {specialType: "", inputType: "", inputLength: "", regEx: "^[a-zA-Z]+$", message: "a"…}

但是,如果我使用像这样的正则表达式:^\$?(\d+|\d*.\d+)$

输入的 html 看起来像:

Google chrome 吐出一个像这样的对象:

Object {0: "{", 1: """, 2: "d", 3: "a", 4: "t", 5: "a", 6: "t", 7: "y", 8: "p", 9: "e", 10: """, 11: ":", 12: """, 13: "f", 14: "l", 15: "o", 16: "a", 17: "t", 18: "I", 19: "n", 20: "t", 21: "e", 22: "g", 23: "e", 24: "r", 25: """, 26: ",", 27: " ", 28: """, 29: "m", 30: "e", 31: "s", 32: "s", 33: "a", 34: "g", 35: "e", 36: """, 37: ":", 38: """, 39: "a", 40: """, 41: ",", 42: " ", 43: """, 44: "r", 45: "e", 46: "g", 47: "E", 48: "x", 49: """, 50: ":", 51: """, 52: "^", 53: "\", 54: "$", 55: "?", 56: "(", 57: "\", 58: "d", 59: "+", 60: "|", 61: "\", 62: "d", 63: "*", 64: "\", 65: ".", 66: "\", 67: "d", 68: "+", 69: ")", 70: "$", 71: """, 72: "}", specialType: "", inputType: "", inputLength: "", regEx: "", message: ""}

我不知道为什么。我试过在正则表达式的开头和结尾加上/,但这也不起作用。任何帮助将不胜感激。

最佳答案

这是因为\是一个转义字符。您将不得不通过在它之前放置另一个\来逃避它。所以你需要把\\放在你的数据属性中。

关于数据属性中的 Javascript 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333423/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com