我正在制作自定义表单验证插件。它使用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 chromes控制台中打印,如:
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: ""}
我不知道为什么。我已经尝试使用/在开头和结尾添加正则表达式,但这也不起作用。任何帮助将不胜感激。
答案 0 :(得分:2)
这是因为\是一个转义字符。你必须通过在它之前放置另一个\来逃避它。所以你需要把\\放在你的数据属性中。