user2112618
user2112618

Reputation: 326

Javascript regex in data attributes

I am in the process of making a custom form validation plugin. It is using the HTML5 data attribute that is placed within each input where special parameters need to be met. example:

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

The initial data object is coming into the javascript just fine but when I extend the object under certain custom regex's the extended object is causing errors.

Here is the code snippet that is creating the object:

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);

Now if I use a regex without an \ it works one similar to: ^[0-9]+$

the inputs html will look like:

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

The object that gets extended will then print in google chromes console like:

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

but, if I use a regex like: ^\$?(\d+|\d*.\d+)$

the inputs html will look like:

Google chrome spits out an object like:

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: ""}

I am at a loss as to why. I have tried putting in the regular expression with / at the beginning and end, but that is not working either. Any help would be greatly appreciated.

Upvotes: 1

Views: 1452

Answers (1)

Shreyas
Shreyas

Reputation: 1462

This is because \ is an escape character. You would have to escape it by placing another \ before it. So you need to put \\ in your data attribute.

Upvotes: 2

Related Questions