Wow...I never really got into the whole 'blog on a regular basis while you're in school' thing...oh well.
So today at work I spent an awful amount of time figuring out the following problem (and laughed at myself for a reasonably long amount of time once doing so).
Here's the rub:
Server creates a page with a bunch of controls for the client (using asp). One of these controls needs to do some validation on a textbox using a regular expression, and due to a design decision, javascript was chosen for implementation over the MS spun ASP RegularExpression validator. Great.
VB
textboxinquestion.Attributes.Add("onblur", "doesPassRegExp('^\d+(\.\d{1,2})?$','" & textboxinquestion.ClientID & "','Invalid Field');"
So this dynamically creates a call to the doesPassRegExp function onblur of the textboxinquestion, whilst passing in the regular expression, the textbox itself, and an output message.
This gets passed to the javascript function:
function doesPassRegExp(re, testElem, customOutput) {
if (testElem != null && re != null) {
var reg = new RegExp(re);
if (document.getElementById(testElem).value.match(reg)) {
return true;
} else {
alert(customOutput);
document.getElementById(testElem).value = "";
return false;
}
}
}
...which is syntactically, and programatically fine. Since you're probably Googling like crazy and stumbled across this... the 'backslash' character is an escape character in javascript. SO...once it got passed in it jacks up the regular expression to the point that it breaks and everything falls apart.
Incidentally, if you are using another textbox to put the regular expression in like this:
function demoMatchClick() {
var re = new RegExp(document.demoMatch.regex.value);
if (document.demoMatch.subject.value.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
SOURCE:
http://www.regular-expressions.info/javascriptexample.html
It works fine because the escape characters don't come into play (for some reason...I guess the 'value' member keeps it from processing them since it's never turned into a string. Feel free to leave a comment if you know the real reason why).
Happy hacking!
-pr
PS Sorry for the formatting...I don't want to figure out how to format code in blogspot at the moment...
Friday, December 30, 2011
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment