I have a control that is a date picker with validation using HTML5’s “pattern” attribute with a regular expression. It works fine.
<input type='text' class='date-pick' name='breakEndIE' size='8' placeholder='01-03-2011' style='max-width:100px' pattern='^(((0[1-9]|[12]\d|3[01])-(0[13578]|1[02])- ((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)-(0[13456789]|1[012])-((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])-02-((19|[2-9]\d)\d{2}))|(29-02-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$' readonly='readonly' required />
However when I put it inside a script using document.write() it stops working. (Pattern always thinks there is an error in the formatting of the date)
<script>
var ifFFOCHR = false;
if (navigator.appVersion.indexOf("MSIE") > -1) ifFFOCHR = false;
else if (navigator.appVersion.indexOf("Chrome") > -1) ifFFOCHR = true;
else if (navigator.appVersion.indexOf("Safari") > -1) ifFFOCHR = false;
else ifFFOCHR = true;
if (ifFFOCHR == true)
{
//FIREFOX/CHROME/OPERA CODE HERE
document.write("<input type='text' class='date-pick' name='breakEnd' size='8' placeholder='01-03-2011' style='max-width:100px' pattern='^(((0[1-9]|[12]\d|3[01])-(0[13578]|1[02])-((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)-(0[13456789]|1[012])-((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])-02-((19|[2-9]\d)\d{2}))|(29-02-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$' required />");
}
else
{
//IE/SAFARI CODE HERE
document.write("<input type='text' class='date-pick' name='breakEndIE' size='8' placeholder='01-03-2011' style='max-width:100px' pattern='^(((0[1-9]|[12]\d|3[01])-(0[13578]|1[02])- ((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)-(0[13456789]|1[012])-((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])-02-((19|[2-9]\d)\d{2}))|(29-02-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$' readonly='readonly' required />");
}
</script>
I have no idea why this is happening. I have tried copying and pasting the into the document.write() many times. It works outside it, but not in it. I have tried getting a friend to do it.
We tried it inside another script and it worked fine, it is just inside this script that it breaks.
Please help.
FYI: The script is to make certain code display inside IE & Safari and different code display in Firefox, Opera, and Chrome.
One strong possibility is that you have escape characters e.g.
\din your regex string. Those are treated literal characters when the pattern attribute is added inline, but the\are treated with a different meaning when placed in a javascript string.Because you have now wrapped that expression in a string, you likely need to escape the
\character, e.g.\\d.Try writing your string out to
console.logor callingalert()so you can visualise how your string has been interpreted by JavaScript.