473,394 Members | 1,724 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

help with RegEx

hello,

i need a regular expression for my form-validation:

it should be allowed to fill a <input type="text"with

any iteger number up to 500
or
a integer number up to 500 followed by px (e.g. "200px")
or
a integer number up to 85 followed by % (e.g. "45%")

anything else should be returned false with a alert-message.
i'm not good in RegEx and i didn't find a example for that online.
maybe someone here can help me?

thanks a lot,
Martin Nadoll
Jun 27 '08 #1
8 1165
* Martin Nadoll wrote in comp.lang.javascript:
>i need a regular expression for my form-validation:

it should be allowed to fill a <input type="text"with

any iteger number up to 500
or
a integer number up to 500 followed by px (e.g. "200px")
or
a integer number up to 85 followed by % (e.g. "45%")

anything else should be returned false with a alert-message.
i'm not good in RegEx and i didn't find a example for that online.
maybe someone here can help me?
Unless you absolutely have to use a regular expression, this is best
done by converting the strings to a suitable number and check that
instead. A regex would look like

* 500 optionally followed by px, or
* 4 or 3 or 2 or 1 optionally followed
by 1 or 2 digits optionally followed by px, or
* ...

Which isn't particularily pretty in comparison (think about how to
change or proof-read it in the future).
--
Björn Höhrmann · mailto:bj****@hoehrmann.de · http://bjoern.hoehrmann.de
Weinh. Str. 22 · Telefon: +49(0)621/4309674 · http://www.bjoernsworld.de
68309 Mannheim · PGP Pub. KeyID: 0xA4357E78 · http://www.websitedev.de/
Jun 27 '08 #2
VK
On Apr 26, 8:00 pm, "Martin Nadoll" <mar...@nadoll.dewrote:
hello,

i need a regular expression for my form-validation:

it should be allowed to fill a <input type="text"with

any iteger number up to 500
or
a integer number up to 500 followed by px (e.g. "200px")
or
a integer number up to 85 followed by % (e.g. "45%")

anything else should be returned false with a alert-message.
i'm not good in RegEx and i didn't find a example for that online.
In such case maybe it is better to use straightforward if-else check
instead. The code you can understand is much easier to maintain and to
update plus much lesser risk of occasional typos.
n = document.forms['MyForm'].MyElement.value;

if ((+n < 0) || (parseInt(n) != +n)) {
return false;
}
if ((n.lastIndexOf('%') != -1) && (+n <= 85)) {
return true;
}
else if ((n.lastIndexOf('%') == -1) && (+n <= 500)) {
return true;
}
else {
return false;
}
Jun 27 '08 #3
Martin Nadoll wrote on 26 apr 2008 in comp.lang.javascript:
hello,

i need a regular expression for my form-validation:

it should be allowed to fill a <input type="text"with

any iteger number up to 500
or
a integer number up to 500 followed by px (e.g. "200px")
or
a integer number up to 85 followed by % (e.g. "45%")

anything else should be returned false with a alert-message.
i'm not good in RegEx and i didn't find a example for that online.
maybe someone here can help me?
<script type='text/javascript'>

var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^(((8[0-5])|([1-7]\d)|[1-
9])\%)$/;

function testMe(f){
if (re.test(f.elements['myField'].value))
return true;
alert('Something rotten in myField');
return false;
};

</script>

<form onsubmit='return testMe(this)'>
<input type="text" name='myField'>
</form>

=====================

It seems that the present mood is, that because Regex is unreadable for a
later moronic reviewer of your code, so should not be used.
I do not agree.
Perhaps the exploded view below provides additional explanation:

^
(
(
(500)|
([1-4]\d\d)|
([1-9]\d?)
)
(px)?
)
$
|
^
(
(
(8[0-5])|
([1-7]\d)|
[1-9]
)
\%
)
$

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 27 '08 #4
In comp.lang.javascript message <48**********************@newsspool2.arc
or-online.net>, Sat, 26 Apr 2008 18:00:05, Martin Nadoll
<ma****@nadoll.deposted:
>hello,

i need a regular expression for my form-validation:

it should be allowed to fill a <input type="text"with

any iteger number up to 500
or
a integer number up to 500 followed by px (e.g. "200px")
or
a integer number up to 85 followed by % (e.g. "45%")

anything else should be returned false with a alert-message.
i'm not good in RegEx and i didn't find a example for that online.
maybe someone here can help me?
The best way is to RegExp-match the general pattern, of digits followed
optionally by px or %, followed by specific-to-case code. The .match
combines matching pattern, splitting into fields, ensuring non-negative.

Would 0240px be allowed? it fits your description.

Consider and test

var U

Num = Str = Max = U

Pattern = VALUE.match(/^(\d+)(%|px)?$/)
if (Pattern) {
Num = +Pattern[1] ; Str = Pattern[2]
Max = Str=="%" ? 85 : 500 }

A = [ !!Pattern, Max, Num, Str, Num<=Max ]

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.

--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE7 FF2 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jun 27 '08 #5
"Evertjan." <ex**************@interxnl.netwrites:
var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^(((8[0-5])|([1-7]\d)|[1-
9])\%)$/;
Good example of why not to use RegExp's for numerical comparison :)
It's almost unreadable, and it still doesn't match 0px (although that
could be by design).

function testMe(f) {
var match = f.match(/^(\d+)(px|%)?$/);
if (!match) { return false; }
var num = +match[1];
switch(match[2]) {
case '%': return num <= 85;
case 'px':
default:
return num <= 500;
}
}
It seems that the present mood is, that because Regex is unreadable for a
later moronic reviewer of your code, so should not be used.
Not hard to read, but hard to modify too, although that is related.
I do not agree.
I do. Making code maintainable is important, to later "moronic
reviewers" (aka, your esteemed collegues and yourself in 30 days).

Try changing the limit from 85 to 125, and consider how many places
you need to change. Maintainable code should only need to change in
one place, where "85" is replaced by "125".

For added credit, I should have created them as constants instead
of inlined literals.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #6
Lasse Reichstein Nielsen wrote on 27 apr 2008 in comp.lang.javascript:
"Evertjan." <ex**************@interxnl.netwrites:
>var
re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^(((8[0-5])|([1-7]\d)|[1-
9])\%)$/;

Good example of why not to use RegExp's for numerical comparison :)
It's almost unreadable, and it still doesn't match 0px (although that
could be by design).
Tast was my design, it would be simpler without restricting the zero.

re=/^(((500)|([1-4]\d\d)|([1-9]?\d))(px)?)$|^(((8[0-5])|([1-7]?\d))\%)$/;

function testMe(f) {
var match = f.match(/^(\d+)(px|%)?$/);
if (!match) { return false; }
var num = +match[1];
switch(match[2]) {
case '%': return num <= 85;
case 'px':
default:
return num <= 500;
}
}
>It seems that the present mood is, that because Regex is unreadable
for a later moronic reviewer of your code, so should not be used.

Not hard to read, but hard to modify too, although that is related.
>I do not agree.

I do. Making code maintainable is important, to later "moronic
reviewers" (aka, your esteemed collegues and yourself in 30 days).
No, it is only important in your environment, but not in mine.

I, and many others I surmize, code for personal joy, compactness and
elegance, and mastering the Regex is a joy in itself.

I could not care less, if my code is unreadable if I am not around.
Throw it away, throw it away, throw it away!

After a few years I love to start from scratch and incorporate all the
new methods I learned or developed to get the same result perhaps in a
more elegant way.
Try changing the limit from 85 to 125, and consider how many places
you need to change. Maintainable code should only need to change in
one place, where "85" is replaced by "125".
Ah, an added challenge, I would like that.

OK, warn for lack of maintainability,
but don't dismiss the pleasure of such coding per se.

In my assembler days, each line had one or more comment lines to make it
readable, but those days are gone. Dreadfull sorry, Clementine? Perhaps.

However I am not even against the Javascript equivalents of the ancient
BASIC left(), mid(), right() and the less old instr(). With a lot of
code, you can get the same results.

3 or 4 years ago I could not "do" regex, and I didn't miss it, but you
never miss what you do not know.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 27 '08 #7
In comp.lang.javascript message <Xn*******************@194.109.133.242>,
Sat, 26 Apr 2008 19:10:11, Evertjan. <ex**************@interxnl.net>
posted:
>
var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^(((8[0-5])|([1-7]\d)|[1-
9])\%)$/;
Rejects zero, which the OP's wording did not call for.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQqish topics, acronyms & links;
Astro stuff via astron-1.htm, gravity0.htm ; quotings.htm, pascal.htm, etc.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jun 27 '08 #8
Dr J R Stockton wrote on 27 apr 2008 in comp.lang.javascript:
In comp.lang.javascript message <Xn*******************@194.109.133.242>,
Sat, 26 Apr 2008 19:10:11, Evertjan. <ex**************@interxnl.net>
posted:
>>
var re=/^(((500)|([1-4]\d\d)|([1-9]\d?))(px)?)$|^(((8[0-5])|([1-7]\d)|[1-
9])\%)$/;

Rejects zero, which the OP's wording did not call for.
Methinks that is implicit, but the alternative was already posted:

re=/^(((500)|([1-4]\d\d)|([1-9]?\d))(px)?)$|^(((8[0-5])|([1-7]?\d))\%)$/;
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Tony C | last post by:
I'm writing a python program which uses regular expressions, but I'm totally new to regexps. I've got Kuchling's "Regexp HOWTO", "Mastering Regular Expresions" by Oreilly, and have access to...
8
by: Bibe | last post by:
I've been trying to get this going for awhile now, and need help. I've done a regex object, and when I use IsMatch, it's behavior is quite weird. I am trying to use Regex to make sure that a...
4
by: H | last post by:
This is kind of an followup on oneof my previous questions, and it has with RegEx to do. I have a string containing of several words. What would a good regex expression looklike to get one match...
6
by: Dave | last post by:
I'm struggling with something that should be fairly simple. I just don't know the regext syntax very well, unfortunately. I'd like to parse words out of what is basically a boolean search...
4
by: henrik | last post by:
Hi I have a regex question. I want to find all content of a <td class="someclass"> tag. This means the expression should include all other tags included between <td class="someclass"> and </td>....
9
by: jmchadha | last post by:
I have got the following html: "something in html ... etc.. city1... etc... <a class="font1" href="city1.html" onclick="etc."click for <b>info</bon city1 </a> ... some html. city1.. can repeat...
2
by: Alex Maghen | last post by:
This is a bit of an abuse of this group. Just a nit, but I'm hoping someone really good with Regular Expressions can help me out here. I need to write a regular expression that will do the...
3
by: =?Utf-8?B?TmF2ZWVu?= | last post by:
Not sure if this is the right forum for this question but couldn'd find another newsgroup. I am new to Regular expressions and would like help in deciding which pattern allows me to split a...
10
by: supercrossking | last post by:
I am trying to the values of string of text in the sample before. The ds are for digits and s is for string and string of text is for a string with more than one or two values. I am trying to use...
0
by: Support Desk | last post by:
That’s it exactly..thx -----Original Message----- From: Reedick, Andrew Sent: Tuesday, June 03, 2008 9:26 AM To: Support Desk Subject: RE: regex help The regex will now skip anything with...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.