RegExp - Build dynamic pattern

Z

zbig555z

Hello: I have written an ASP.net app that pulls settings from a
database. Part of the setting definition is a regular expression that
I want to use on the client via JavaScript for data validation...


1) Sample code for the setting object:
----------------------------------------------------
function setting(id, name, validationPattern, validationMsg) {
this.id = id;
this.name = name;
this.validationPattern = validationPattern;
this.validationMsg = validationMsg;
}


2) Sample code on the page that creates a new setting object:
----------------------------------------------------
setting(1, 'test', '^\\d{1,1}$|^\\d{2,2}$|^100$', 'invalid value');


3) The issue:
----------------------------------------------------
The setting object gets built just fine except the pattern argument
gets escaped by javascript!!!

^\\d{1,1}$|^\\d{2,2}$|^100$

GETS ESCAPED TO

^\d{1,1}$|^\d{2,2}$|^100$ (Notice how the double \\ is now a single \)


Is there any way for me to preserve the pattern text as is?

Thank you,
zbig555z
 
M

Mick White

zbig555z said:
Hello: I have written an ASP.net app that pulls settings from a
database. Part of the setting definition is a regular expression that
I want to use on the client via JavaScript for data validation...


1) Sample code for the setting object:
----------------------------------------------------
function setting(id, name, validationPattern, validationMsg) {
this.id = id;
this.name = name;
this.validationPattern = validationPattern;
this.validationMsg = validationMsg;
}


2) Sample code on the page that creates a new setting object:
----------------------------------------------------
setting(1, 'test', '^\\d{1,1}$|^\\d{2,2}$|^100$', 'invalid value');


3) The issue:
----------------------------------------------------
The setting object gets built just fine except the pattern argument
gets escaped by javascript!!!

^\\d{1,1}$|^\\d{2,2}$|^100$

A literal js regex should look something like this:

/^\\d{1,1}$|^\\d{2,2}$|^100$/

The regex above looks rather strange, are you looking for any positive
number between "0" and "100"(inclusive)?

/(^\d\d?$)|(^100$)/


<script type="text/JavaScript">
var x="";
for(i=0;i<105;i++){
x+=i+": "+/(^\d\d?$)|(^100$)/.test(i)+"<BR>";
}
document.write(x)
</script>
A little crude, perhaps, it allows "0" and "00".
Mick
 
Z

zbig555z

Thanks for the reply...This worked...

the heart of the issue is that I was writing out the patterns as
strings not literal RegEx objects.

I changed

'pattern' to /pattern/ and all is good.

Thanks again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top