By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,930 Members | 633 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,930 IT Pros & Developers. It's quick & easy.

Simple Regular Expression need

P: n/a
I have Vidation Controls

First One: Simple exluce certain special characters:
say no a or b or c in the string:
[^abc]*

Second One:
I required date be entered in "MM/DD/YYYY" format:
[0-1][0-9]/[0-3][0-9]/[0-9]+4 How ??

Nov 19 '05 #1
Share this Question
Share on Google+
18 Replies


P: n/a

just don't use the validation controls

and it will be easy

and there isn't much point in using regex
to validate dates - you will have to parse
it at some point anyway - why not let
the date parser do its job?

and then you can do your own date sanity check as well

(yet another example of asp.net controls complicating a simple task :)

Nov 19 '05 #2

P: n/a
Q:
Take a look at http://www.regexlib.com/, you should be able to find what
you're looking for there.

HTH

Mr. Rivers:
As for not using the validation controls, why not let them do their job?
You argue (actually, that's most of what you seem to do here) that "there
isn't much point in using regex to validate dates." Here are some good
reasons to use regular expressions to validate a date:

1.) DateTime.Parse() is not available on the client. You have
complained about the way that Visual Studio/ASP.NET don't let you inline
HTML and JavaScript in a code block in the ASPX so it can be implied that
you use JavaScript in at least some of your applications. Granted, a user
may have JavaScript disabled but why should you punish those users that
don't by forcing a postback that ends up doing nothing more than telling the
user that their input is invalid when a couple of lines of JavaScript could
do the same thing without the postback. The postback can be particularly
troublesome for those users on a dial-up connection since the round trip
will take significantly longer than executing a couple lines of JavaScript.
Should the input be double checked on the server? Absolutely, but that
doesn't mean that the data should not be checked ahead of time to reduce
your server's workload a bit too. [The javascript function Date.parse() is
an alternative but is quirky at best and would require using two separate
validation routines (client and server) rather than letting the validation
control do its job].

2.) When the input is in an incorrect format, DateTime.Parse() throws an
exception which must then be handled (expensive) and ends up bloating your
code (something you seem to not be too fond of based on some of your
previous posts) with try/catch blocks. Instead, one may choose to use
Regex.IsMatch() which returns a boolean that can be tested against before
calling DateTime.Parse() and avoids the overhead associated with exception
handling.

----------------
Dave Fancher
http://www.davefancher.com

"John Rivers" <fi*****@btinternet.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...

just don't use the validation controls

and it will be easy

and there isn't much point in using regex
to validate dates - you will have to parse
it at some point anyway - why not let
the date parser do its job?

and then you can do your own date sanity check as well

(yet another example of asp.net controls complicating a simple task :)

Nov 19 '05 #3

P: n/a
"John Rivers" <fi*****@btinternet.com> wrote in
news:11**********************@g49g2000cwa.googlegr oups.com:
and there isn't much point in using regex
to validate dates - you will have to parse
it at some point anyway - why not let
the date parser do its job?

Because regex is an efficent way to do validation - both on the server AND
client.

And regex can do "parsing" as well - you can have group matching within a
regex expression, so there's no real need to parse.

--
Lucas Tam (RE********@rogers.com)
Please delete "REMOVE" from the e-mail address when replying.
http://members.ebay.com/aboutme/coolspot18/
Nov 19 '05 #4

P: n/a
To me, Validation controls are great feature. they allow the seperation
of the validation logic and the business logic hence make the code much
cleaner.

I am not familiar with Regular Expression and I am on a tight project
with not much time read a tutorial. I need some real code (expression
in this case) just to plug in to make it work. I will read Dave's link
later.

Question 1: I need a Regular Expression that disallow certain
charactors in a string. Eg. not allow a, b, and c.
I come up with [^abc]* , is it correct?

Question 2: I need a Regular Expression that validate a date format of
"MM/DD/YYYY".

p.s. For date format, I could use Comparision Validator control to
verify it it is a type of Date/Time. But I am concerned that there
could be problem with international users.

Thanks

John

Nov 19 '05 #5

P: n/a
I finally looked at reglib.com and found what I wanted. Have to go
through a Quick-Start to understand and tweak a little bit.

Thanks

John

Nov 19 '05 #6

P: n/a
Good! I was in the process of typing a reply.

For the date matcher, you could use:
^((\d{2}/){2}\d{4})$
Matches MM/DD/YYYY

...or, if you decide that you want to allow single digits for day and month
(1 instead of 01), you could use:
^((\d{1,2}/){2}\d{4})$
Matches MM/DD/YYYY, M/DD/YYYY, MM/DD/YYYY, or M/D/YYYY

The examples on regexlib are probably closer to what you're looking for
though since they're a bit more specific. If you still need help with your
character exclusion, you'll need to be more specific about what you're
trying to exclude and what type of input you expect to receive.

HTH
----------------
Dave Fancher
http://www.davefancher.com

"Q. John Chen" <qj****@email.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
I finally looked at reglib.com and found what I wanted. Have to go
through a Quick-Start to understand and tweak a little bit.

Thanks

John

Nov 19 '05 #7

P: n/a
Hi John,
Question 1: I need a Regular Expression that disallow certain
charactors in a string. Eg. not allow a, b, and c.
I come up with [^abc]* , is it correct?
That regex will match text that has not a,b or c in it.

So abccb wil not match but abcdefgabc will match efg.

If you want to disalow input that contains a,b or c you can use :

^[^abc]*$
Here you state that everything between the beginning of the string (^) and
the end ($) may not contain a,b or c.

Question 2: I need a Regular Expression that validate a date format of "MM/DD/YYYY".

The solutions that Dave present can help. If you want to rule out dates like
45/33/2005 I can come up with a complex regex if you need it.
Than again, a regex can't rule out 31/2/2005. If you want to validate dates
stricter (including leap years) I think there are some javescript functions
you can rely on.
But I think the more simpler regexes suffice.

Let me know if you have any more questions...

Cheers,
Tom Pester
To me, Validation controls are great feature. they allow the
seperation of the validation logic and the business logic hence make
the code much cleaner.

I am not familiar with Regular Expression and I am on a tight project
with not much time read a tutorial. I need some real code (expression
in this case) just to plug in to make it work. I will read Dave's link
later.

Question 1: I need a Regular Expression that disallow certain
charactors in a string. Eg. not allow a, b, and c.
I come up with [^abc]* , is it correct?
Question 2: I need a Regular Expression that validate a date format of
"MM/DD/YYYY".

p.s. For date format, I could use Comparision Validator control to
verify it it is a type of Date/Time. But I am concerned that there
could be problem with international users.

Thanks

John

Nov 19 '05 #8

P: n/a
I think that I got, by tweak one in regexlib.com a RegEx that take are
of the date format except Feb 29. (need test when back to work).
Thanks all !!!

Nov 19 '05 #9

P: n/a


Dear Dave,

thankyou for your response, i enjoy an intelligent discussion,
and contrary to popular opinion, i am happy to be proved wrong,
because that would mean i have learnt something - and that is
my passion :)

Please see my comments below

John

Dave Fancher wrote:
Q:
Take a look at http://www.regexlib.com/, you should be able to find what
you're looking for there.

HTH

Mr. Rivers:
As for not using the validation controls, why not let them do their job?
You argue (actually, that's most of what you seem to do here) that "there
isn't much point in using regex to validate dates." Here are some good
reasons to use regular expressions to validate a date:

1.) DateTime.Parse() is not available on the client. You have
complained about the way that Visual Studio/ASP.NET don't let you inline
HTML and JavaScript in a code block in the ASPX so it can be implied that
you use JavaScript in at least some of your applications. Granted, a user
may have JavaScript disabled but why should you punish those users that
don't by forcing a postback that ends up doing nothing more than telling the
user that their input is invalid when a couple of lines of JavaScript could
do the same thing without the postback. The postback can be particularly
troublesome for those users on a dial-up connection since the round trip
will take significantly longer than executing a couple lines of JavaScript.
Should the input be double checked on the server? Absolutely, but that
doesn't mean that the data should not be checked ahead of time to reduce
your server's workload a bit too. [The javascript function Date.parse() is
an alternative but is quirky at best and would require using two separate
validation routines (client and server) rather than letting the validation
control do its job].
All good stuff here, but i have some counterpoints that apply in some
situations.
I do use javascript in my applications, but always ensure that the app
will function with or without it (graceful degradation) for all the
obvious
reasons, furthermore I write it very defensively because a client side
error
is totally unacceptable, and a real risk when javascript couldn't try
catch.
However I almost never validate using javascript, even as a service to
the
constructive user, for these reasons:

a. validation still has to occur at the server
a.1 this means validation logic must be identical in two languages
a.2 you have doubled your work and complexity and develop time
a.3 you have two validation feedback mechanisms for users to deal with
a.4 there might still be roundtrips
a.5 certain types of validation can ONLY occur on the server
(points a.4 and a.5 are relevant because anything that increases
the probability of roundtrips, even when client side validation is in
place,
weakens the value proposition of "viewer roundtrips")

b. client side bugs are a serious risk
every month i come across major websites (symantec.com dabs.com etc.)
that have javascript errors that have inhibited me from spending money
every benefit (no roundtrips) has a potential risk (website doesn't
work)
b.1 tracking client-side bugs is almost impossible
(this means your website might not be working and you well never know
as opposed to server side where you can write a log file or raise an
alarm
although this is also true for html ... javascript is much more fragile
therefore the probability of problems is higher

c. as a general rule you should write your application to support
the "constructive intelligent" user
(this is in contrast to the "destructive user" (who attempts to damage
your system) and the "constructive stupid" user (who wants to consume
your service but is not willing to make any mental effort towards same
however well designed your ui)
c.1 this means that writing lots of code to support people who
are "constructively stupid" is a waste of time
c.2 this means that if your ui is designed and worded correctly
nearly all "constructive users" will populate the form correctly
first time and validation presentation code will hardly ever run
and that is the crux of my point, probability, that probability
of a given user seeing your homepage is usually 100% so we put
effort into that, if only destructive or stupid users are likely
to fail validation, don't waste too much energy on "servicing" them

d. regarding dial-up users
in my humble opinion all web applications should be designed
to work quickly and efficiently over a 14,400 bps connection
this makes my applications rather boring to lookat, but all
my users are happy with performance, if they want to see something
with rich graphics they can insert gta san andreas dvd into their pc!
my job is to make money, not impress people
d.1 thus if a roundtrip on a certain site is such a trauma for users
i recommend energy is spent on solving that problem directly, as
opposed
to increasing complexity


2.) When the input is in an incorrect format, DateTime.Parse() throws an
exception which must then be handled (expensive) and ends up bloating your
code (something you seem to not be too fond of based on some of your
previous posts) with try/catch blocks. Instead, one may choose to use
Regex.IsMatch() which returns a boolean that can be tested against before
calling DateTime.Parse() and avoids the overhead associated with exception
handling.
in brief the problems with using regular expressions include, but are
not limited to:

- to actually come up with a regular expression that can truly only
allow
valid dates is quite hard
- as soon as you need to range check the date, it has to be parsed
anyway
- on the server regex handling is MUCH more expensive than date parsing
(especially with your approach you end up having to do BOTH)
- try catch blocks are never a problem
i hope i you agree there is some value in my counterpoints, if only
in certain circumstances, and that i am not a troll!

All the best,

John


----------------
Dave Fancher
http://www.davefancher.com

"John Rivers" <fi*****@btinternet.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...

just don't use the validation controls

and it will be easy

and there isn't much point in using regex
to validate dates - you will have to parse
it at some point anyway - why not let
the date parser do its job?

and then you can do your own date sanity check as well

(yet another example of asp.net controls complicating a simple task :)


Nov 19 '05 #10

P: n/a
Hi John,

Interesting thread. I strongly agree that you should design validation on
the server side fully and only offer client-side as an enhancement. The
ASP.NET validators do that and in fact, due to the lack of support for
client-side validation on non-DHTML browsers (like FireFox), its essential
to build your site this way. Take a look at this article for all kinds of
hints like this with the ASP.NET validators: http://www.aspalliance.com/699.

In that article, you will learn how to use the CompareValidator to handle
dates with international concerns addressed. It is built to handle it.

--- Peter Blum
www.PeterBlum.com
Email: PL****@PeterBlum.com
Creator of "Professional Validation And More" at
http://www.peterblum.com/vam/home.aspx

"Q. John Chen" <qj****@email.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
To me, Validation controls are great feature. they allow the seperation
of the validation logic and the business logic hence make the code much
cleaner.

I am not familiar with Regular Expression and I am on a tight project
with not much time read a tutorial. I need some real code (expression
in this case) just to plug in to make it work. I will read Dave's link
later.

Question 1: I need a Regular Expression that disallow certain
charactors in a string. Eg. not allow a, b, and c.
I come up with [^abc]* , is it correct?

Question 2: I need a Regular Expression that validate a date format of
"MM/DD/YYYY".

p.s. For date format, I could use Comparision Validator control to
verify it it is a type of Date/Time. But I am concerned that there
could be problem with international users.

Thanks

John

Nov 19 '05 #11

P: n/a
"Peter Blum" <PL****@Blum.info> wrote in
news:u6**************@TK2MSFTNGP14.phx.gbl:
ASP.NET validators do that and in fact, due to the lack of support for
client-side validation on non-DHTML browsers (like FireFox), its
essential to build your site this way.


You can use any scripting language to validate the controls - you're not
necessarily limited to DHTML. If you stick with standard javascript...
don't the client side validators work in Firefox/IE?

Of course you'll still need server-side validation incase the user has
javascript turned off...

--
Lucas Tam (RE********@rogers.com)
Please delete "REMOVE" from the e-mail address when replying.
http://members.ebay.com/aboutme/coolspot18/
Nov 19 '05 #12

P: n/a
John:

I will not disagree regarding that some validation tasks (validation of part
numbers, etc...) cannot be performed client-side but the format thereof
along with certain "illegal" characters certainly can be in most cases. In
my opinion, bad user input should be filtered client-side [whenever
possible] to a.) prevent an unnecessary postback, and b.) prevent bad,
possibly malformed data from being sent to the server if possible.
Furthermore, part of the success/acceptance of any application is the
perception of good performance. If your application can perform at least
most of the validation client-side and therefore prevent some unnecessary
postbacks and server processing, the application will [typically] appear to
the user as being better performing and therefore (whether correctly or not)
perceived to be of higher quality.

In most cases I am all for the most simple solution but there are places
(such as with validation code) where I believe the added complexity will
result in a better overall application and better user experience.

I also disagree with your point regarding two types of "validation feedback"
for users to deal with since if the user has scripting enabled, the
validation code would catch it there and the user would never see the
validation feedback. If the user does not have scripting enabled, the
reverse is true. In situations where the validation can only be performed
server side, writing your code so that the error display follows the same
manner as your client side code would result in a single type of feedback
for users to deal with; just because something has to happen on the server
doesn't mean that is has to look like it.

You're right, client side bugs are a serious risk but that just emphasizes
the need for testing before deployment. Not thoroughly testing code (client
or server side) is nothing short of irresponsible. In my experiences, most
(notice that I said "most") of the script errors on major web sites are not
due to bad scripting work on the part of the site developers but is
typically due to a spyware infection. Tracking client-side bugs is far from
impossible, particularly with the script debugger in VS.

I disagree with your statement about developing for the "constructive
intelligent user" as opposed to the other types you defined. In a perfect
world where everyone would only enter valid input I would be hard-pressed to
come up with counter points but we both know that we're far from that.
Assuming for a moment that all of your users are "constructive intelligent",
people, even the best of us, still make mistakes. Even professional data
entry operators get "fat-fingered" once in a while. Typos are bound to
happen. It is part of our job as professional developers to anticipate what
can go wrong and where. One must assume that anywhere someone can enter
something, that something may be wrong. My philosophy does not extend to
categorizing my users, it simply assumes that users will enter invalid data
that must be accounted for. It is especially important to guard against
your "destructive user" class because these are the ones that will cause the
majority of the problems when the data is not properly checked.

You're absolutely correct in that writing a regular expression for parsing
truly valid date would be nearly impossible to write but when it comes down
to it, a regex is not the correct tool for truly validating a date. Regexs
are meant for pattern matching and they're very good at it. If you're
working on an app that requires a particular format for a date, check that
on the client and let a date parser do the full check where appropriate.
You could even just check the format on the client and let your chosen date
parser do a full check server side, bypassing the formatting check if you're
worried about the [negligable] performance hit from doing both server side.

I did some informal performance tests between the DateTime.Parse() and
Regex.IsMatch() just out of curiosity and found the performance difference
between simply using the DateTime.Parse() and running Regex.IsMatch()
immediately before parsing to be so negligable that even under intense
traffic, the impact probably wouldn't even be noticed.

Not all applications can be written for low speed connections. As an
example, one of the systems that I work on transmits CAD data to our
suppliers. Even zipped, these files are often in excess of 30MB which, at
14.4 takes an estimated 5 hours to complete assuming that the connection
isn't dropped at any time during the transfer. CSS can also make for a
"pretty" site that loads quickly, especially once the stylesheet is cached.

My job is not to make money, making money is my goal. My job (how I go
about achieving my goal) is to produce quality software for my client
whether the client is my full-time employer or a side project. I make more
money when I produce quality software than if I produce poor software or no
software. If I reduce my quality standards or quit making software, I need
a new method to achieve my goal.

---

Now, I prefer to give people the benefit of the doubt but since you brought
up the topic of you being a troll, honestly the idea has crossed my mind. I
believe that you do have some good points in many of your posts and are
capable of adding valuable information to the community (I've seen examples
of it) but posting irrelevant links, insulting people, and trying (at all
costs) to convince people of your intellect and worth as a developer is not
the way to (sorry for the cliche) "win friends and influence people." These
rants about how ASP.NET is "broken," duel challenges, and posts filled with
"ha ha ha ha" because you disagree with the design or methodologies are
unacceptable to the community at large.

When people post a issue, they are not looking to be insulted with comments
like "have you tried balancing it on your head," "delete the data in the
production database then it will run faster," or links to rabid singing
gerbils(?) or McDonalds despite how funny you think they may be (most people
won't see it that way). One must keep in mind that not everyone posting
here is a programmer by trade or even wants to be one for that matter. In
many cases, someone is writing software not because s/he wants to but
because the boss wants the software written and told the person to do it.
Others are simply people trying to get into programming (or the specific
technology) and are just looking for advice on where to begin or
clarification on something that has them bewildered. Many people just want
to get their job done and don't care or even want to know about the low
level details of HTTP, etc...

In fact, most people here aren't looking for a debate either (though they'll
be certain to argue if given reason). The frequent contributors here are
all donating their [hopefully] valuable time to benefit others by sharing
their knowledge. One can learn a lot from reading the posts from the highly
knowledgable people such as Juan Llibre, Steve Orr, Brock Allen, and Kevin
Spencer to name a few (sorry to anyone I missed, these are the names that
immediately come to mind). Their methodologies may not be ones that you
would adopt but they are certainly valid, proven, and help people do their
job.

If you have something to contribute that can benefit the community at large
then by all means, please do so. If, however, you feel it necessary to
resort to behavior such as what I listed above, please go elsewhere or be
prepared to be disrespected, disregarded, and flat out ignored, particularly
by the knowledgable people that frequently contribute valuable information
to the discussions on this group.

One of my favorite sayings is "if all you have is a hammer, everything looks
like a nail," I think this fits system architecture perfectly in that it
all boils down to using the right tool for the job. Right tool doesn't have
to be the same tool for everyone either. If you think that traditional ASP
(or a similar technology like PHP) is the correct tool and methodology to do
your job then, by all means, use it to do your job but do not expect that
those that have adopted a different technology and/or methodology to agree.
;)

I won't claim to be the best or most knowledgable programmer in the world.
I won't even claim that my methodologies are the best way to do something.
What I do is share what I know and what has worked for me in my projects.
If I learn something new in the process (a regular occurance), more power to
me.

Regards,
Dave Fancher
http://www.davefancher.com
Nov 19 '05 #13

P: n/a
Thankyou for taking the time to reply, I read it with great enthusiasm
:)

It got the cogs turning, even added some new cogs.

I am still keen to have a constructive discussion about code blocks in
methods and classes.

I still can see no sensible way to implement my rendering logic any
other way.

Of course I understand if you are busy or tire of the topic.

Nov 19 '05 #14

P: n/a
Hi Morgan,

You have been careless. Do you have a split personality or something Mr.
Rivers?
Complementing yourself rofl :)
Cheers,
Tom Pester
Thankyou for taking the time to reply, I read it with great enthusiasm
:)

It got the cogs turning, even added some new cogs.

I am still keen to have a constructive discussion about code blocks in
methods and classes.

I still can see no sensible way to implement my rendering logic any
other way.

Of course I understand if you are busy or tire of the topic.

Nov 19 '05 #15

P: n/a
darn it, got caught :(

Nov 19 '05 #16

P: n/a
John Rivers wrote:
[snip]

a. validation still has to occur at the server
a.1 this means validation logic must be identical in two languages
a.2 you have doubled your work and complexity and develop time
a.3 you have two validation feedback mechanisms for users to deal with
a.4 there might still be roundtrips
a.5 certain types of validation can ONLY occur on the server
(points a.4 and a.5 are relevant because anything that increases
the probability of roundtrips, even when client side validation is in
place,
weakens the value proposition of "viewer roundtrips")

But the validation controls provide a lot of this for you, at little
cost. You tell them "I want this validation performed", and they work
out whether to do it on the Client side, the Server side, or both.
They've been tested. Lots.

I'm not saying that they are the be-all-and-end-all, but if,say, you
need to ensure a field is filled, that it matches a regular expression,
that the password and confirmation of the password are equal (and that
the password reminder isn't equal to the password), then using them
saves time and thought work - leaving you to put the thinking into the
important parts of the site which are going to differentiate it from
other sites offering similar services.

So yes, for more complex validation you may end up writing code - often
the same amount of code you'd have to write without using the
validation controls. But you can hook your code into a Custom
Validator, and have it present it's feedback identically to the other
controls - still saving you some development time (and if you've
provided client-side script, some round trips as well).

Damien

Nov 19 '05 #17

P: n/a

Thanks Peter, for your post and useful links,

Now for my next "killer" validation point.

Validation is a business logic function, not a presentation function.

The presentation layer's role in validation is to "present" validation
messages to the user, not to conduct validation itself.

Thus the whole concept of "Validation Controls" is mostly a nonsense -
except for low-end websites like marketing/brochure sites.

If you want to see how an absolute top-end revenue-critical web
application does it, look at www.paypal.com.

You won't see client side or presentation layer validation anywhere -
for all the reasons I gave before.

Again, I restate my original point, many parts of ASP.NET are VERY
badly architected and should be avoided.

They are: ASPX (is missing methods and classes), HtmlControls,
UserControls, ServerControls, ValidationControls, ViewState and
probably more ...

Stick to the good stuff and write letters of complaint about the bad,
don't believe microsoft msdn propaganda, not everybody at microsoft is
good at their job.

Nov 19 '05 #18

P: n/a
"Morgan Bachu" <ds********@tiscali.co.uk> wrote in
news:11*********************@g44g2000cwa.googlegro ups.com:
Now for my next "killer" validation point.

Validation is a business logic function, not a presentation function.

The presentation layer's role in validation is to "present" validation
messages to the user, not to conduct validation itself.


Client side validation is a usability feature... It's nice to give the user
a validation message before they submit - it saves the user time.

Server side validation is where you'll call your business logic validation
functions...

--
Lucas Tam (RE********@rogers.com)
Please delete "REMOVE" from the e-mail address when replying.

Newmarket Volvo Sucks! http://newmarketvolvo.tripod.com
Nov 19 '05 #19

This discussion thread is closed

Replies have been disabled for this discussion.