Regular expression for carriage return/enter?

S

stevewy

If the following line will force the user to input only a number
between 1 and 5, and will give an error to any keypress outside that
range:

onkeyup="if(event.srcElement.value.search(new RegExp('^[1-5]$')))
{alert('Please type in a number between 1 and
5');event.srcElement.value='';return false}"

.... how could I get the regular expression to accept 1 to 5 *or* the
Enter/Return keypress? I have tried ('^[1-5][\r]$') but that doesn't
work. Is there a syntax for saying "1 to 5 or Enter/Return"?

Thank you for any info you can give.

Steve
 
S

stevewy

Ah - figured it out: I'm barking up the wrong tree because the
"value" of the source element will never "equal" a Return character.
I needed to do: (new RegExp('^[1-5]$'))&&event.keyCode!=13)

Well, hopefully this post may be of use to anyone else looking for a
similar solution.

Steve
 
T

Thomas 'PointedEars' Lahn

If the following line will force the user to input only a number
between 1 and 5, and will give an error to any keypress outside that
range:

onkeyup="if(event.srcElement.value.search(new RegExp('^[1-5]$')))
{alert('Please type in a number between 1 and
5');event.srcElement.value='';return false}"

This is error-prone, incompatible, illegible, and inefficient. You were
looking for

maxlength="1"
onkeyup="if (!/[1-5]/.test(this.value))
{
window.alert('Please type in a number between 1 and 5');
this.value = '';
return false;
}"

instead. It is still awful. For example, I have just switched from that
focused control to the newsreader with Alt+Tab and got the error message.


PointedEars
 
B

Bart Van der Donck

I'm barking up the wrong tree because the "value" of the source
element will never "equal" a Return character.
I needed to do: (new RegExp('^[1-5]$'))&&event.keyCode!=13)

Take this code Ad Unicem and it might not work anymore; the Enter-key
can give keycode 10 too.

10 = Carriage Return, as described in your subject line
13 = Newline, the most common keycode for the Enter-key AFAIK

... && event.keyCode != 10 && event.keyCode != 13
 

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
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top