Question

regular expressions in java script

Asked by: simi

Please provide exact code to implement:
1. changing lower to upper char when entered by user
2. allow entering only digits
3. allow entering only letters and spaces

eg.

I have a text field and I need the code to put , say onkeyup .....

I need to simply block the user from entering unwanted chars, not to allow, then display an error messatge.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-10-13 at 20:55:24ID22891832
Tags

regular

,

expression

Topic

Regular Expressions

Participating Experts
2
Points
125
Comments
18

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Convert a char to upper case
    What is the best way to make a char variable upper case? It's not that hard when I have a string (MakeUpper() is built in to CString). But it's different with just a char. I tried CString(charCurrent).MakeUpper() And got the error error C2120: 'void' illegal with all t...
  2. AbstractButton.setMnemonic(char)
    Any ideas why AbstractButton.setMnemonic(char) converts lowercase char to upper case? public void setMnemonic(char mnemonic) { int vk = (int) mnemonic; if(vk >= 'a' && vk <='z') vk -= ('a' - 'A'); setMnemonic(vk); } This forces the user to press alt+...
  3. Hex to char conversion in java?
    Hi, My query is : can i convert something in Hex format to char in java? i.e (HEX to CHAR).is there any api to convert from Hex to char?? an small example will be useful. Thanks Lalit
  4. onkeyup auto currency format
    Ok... this is a little tricky! I need a code that would allow user to input a value and as he/she types the number it should automatically insert commas and decimal points for examlpe: if I enter 1 the result would be 1.00 if I enter 1234 the result should be 1,234.00 and ...
  5. CHAR to upper
    I have tried to use strupr(char) and it worked on vs.net's c++, but once I compiled on Linux it didn't work. Is there another function to change a char[4] to all uppercase?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: b0lsc0ttPosted on 2007-10-13 at 21:14:11ID: 20072813

Does this have to be on a key event?  I suggest you use the onblur event in the input element ...

1.  onblur="this.value = this.value.toLowerCase();"
2.  onblur="this.value = this.value.match(/^\d+$/);"
3.  onblur="this.value = this.value.match(/^[A-Z ]/i);"

Let me know if this has to be when the key is pressed.  That involves more script.  An alert can be added if needed but the code above will just remove any invalid characters.

bol

 

by: b0lsc0ttPosted on 2007-10-13 at 21:25:48ID: 20072837

I left something out of the 3rd suggestion.

3.  onblur="this.value = this.value.match(/^[A-Z ]+/i);"

bol

 

by: b0lsc0ttPosted on 2007-10-13 at 21:26:28ID: 20072839

Oops.  Hit submit too quick, forgot the other thing I left out.

3.  onblur="this.value = this.value.match(/^[A-Z ]+$/i);"

 

by: b0lsc0ttPosted on 2007-10-13 at 21:30:18ID: 20072847

If you want to do it in an onkey event with an alert then the functions below go in the script tags in the head part of the html.  The event to call the function is below the functions.

funtion chkKeyLower(e) {
      var k = (e.keyCode)? e.keyCode : e.which;
      if (k < 97 || k > 122) {
            alert('Please use only lowercase characters.');
            return false;
      }
                 return true;
}
funtion chkKeyDigit(e) {
      var k = (e.keyCode)? e.keyCode : e.which;
      if (k < 48 || k > 57) {
            alert('Please use only digit characters.');
            return false;
      }
                 return true;
}
funtion chkKeyLetterSpace(e) {
      var k = (e.keyCode)? e.keyCode : e.which;
      var kName = String.fromCharCode(k);
      if (!kName.match(/^[A-Z ]+$/i)) {
            alert('Please use only alpha characters or a space.');
            return false;
      }
                 return true;
}

You would call any of the function with an onkey event like ...

onkeyup="return chkKeyLower(event);"

Let me know if you have a question.

bol

 

by: simiPosted on 2007-10-13 at 21:41:26ID: 20072866

I want it on key up, so that each time an illegal char is beig entered, to be rejected, but the previous ones are lefe there.
I had the code but can't find it.
It is possible, and it id done on keyup.

 

by: b0lsc0ttPosted on 2007-10-13 at 21:46:33ID: 20072878

My last post will do it then.  Use the function you need for 1, 2, or 3.  The example of the onkeyup event shows the 1st.

Let me know if you have a question.

bol

 

by: simiPosted on 2007-10-14 at 08:08:15ID: 20073966

It does not work.
I asked, for a working code, not hints.
even your keyword is funtion, so I had to correct it.
I clearly stated that I do not want behavior that pops up error messages, but simpl,y stops the char entered if not legal.
What your code does, egl for the chkKeyLower, it wrongfully pops up the message all the time, as it appears that the comparison of what number each char is mapped to is not correct, and it still allows the char to remain in the text field.

 

by: b0lsc0ttPosted on 2007-10-15 at 10:09:42ID: 20079714

>> I clearly stated that I do not want behavior that pops up error messages, <<

I don't know what you mean by "clearly stating" but what you said there directly contradicts what you said in your question body.  You said "then display an error messatge" so I provided an alert.  Removing it is easy but don't blame me for it being there!

I did have a big typo, misspelled the word function, and I made another minor change.  The minor change is probably not needed the typo and using keyup were the big issues.  To do what you want you should use onkeypress.  Sorry about not catching that earlier.

I have a complete, working page below.  I removed the alerts since it seems you don't want them now.  You can add them back if you change your mind again. :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<link href="../style.css" rel="stylesheet" type="text/css" />
<title>Chk entry</title>
<script type="text/javascript">
function chkKeyLower(e) {
      var k = (e.which)? e.which : e.keyCode;
      if (k < 97 || k > 122) {
            return false;
      }
      return true;
}
function chkKeyDigit(e) {
      var k = (e.which)? e.which : e.keyCode;
      if (k < 48 || k > 57) {
            return false;
      }
      return true;
}
function chkKeyLetterSpace(e) {
      var k = (e.which)? e.which : e.keyCode;
      var kName = String.fromCharCode(k);
      if (!kName.match(/^[A-Z ]+$/i)) {
            return false;
      }
      return true;
}
</script>
</head>

<body>
<h3>Check the input</h3>

<br /><br />
<form name="form1" action="" method="post">
Only lower: <input type="text" name="input1" onkeypress="return chkKeyLower(event);" /><br />
Only digit: <input type="text" name="input2" onkeypress="return chkKeyDigit(event);" /><br />
Only alpha or space: <input type="text" name="input3" onkeypress="return chkKeyLetterSpace(event);" /><br />
</form>

</body>
</html>

Let me know if you have a question about this or need more info.  If there is some problem or question you might think about using a little nicer approach, I am not helping here for the abuse and I have better places to spend my limited time if you don't appreciate what I do.

bol

 

by: simiPosted on 2007-10-15 at 19:57:18ID: 20082927

Perhaps the comma confused you , I stated that I do not want to allow the llegal char entered then display an error messaege.
Anyway, I found the solution.
So I will delete the question.
Your suggestion does not work in certain scenarios, mainly because it uses the onkeydown event.
I have no time to go into details.
My initial question asked for a solution onkeyup.
So no hard feelings.

 

by: b0lsc0ttPosted on 2007-10-15 at 21:01:24ID: 20083135

>> Perhaps the comma confused you  <<

The problem was a lot more than a comma.  Even removing the "phrase" your commas were meant to mark the meaning is still the same as I read it at first.  The issue was the sentence itself, just like the "sentence" after the phrase I quoted above.  I don't mind you changing it or saying it wasn't clear but don't blame me for reading it wrong or for a mistake.

>> it uses the onkeydown event <<

No!  It uses the keypress event.  For a keyup event to work it would need to "erase" the value if the validation failed; the keyup is after the key's value is added.  Truly blocking the character from being entered needs an event before keyup, etc.  That makes the script much more complex and likely to fail.  If there is a reason the keypress event won't work then please elaborate.

>> So I will delete the question. ... I have no time to go into details. <<

You will need to be specific on the solution you did use if you want a refund and this deleted/PAQ'd.  The code above is a working solution for what you asked.  I'm glad you got a solution but, with how this has gone, I'm not sure it didn't involve my post.

bol

 

by: simiPosted on 2007-10-16 at 10:52:54ID: 20087532

I have no time to argue with you.
Your script does not work with IE version 6 if (but worked with Mozilla based brws.),/.
IE has the pop-up blocked, even if you do not pop up something, for some reason, the top bar display a message and nothing happens. I will not go with further explination on that.
I am not answering questions here, I asked one.
But still, here is the working code I was looking for
function upper(textField) {
      textField.value = textField.value.toUpperCase();
}

Against your oppinionn, is even more simple then yours.

I will not continue this argument with you.

All the best.

 

by: b0lsc0ttPosted on 2007-10-16 at 19:44:49ID: 20090481

I never wanted to argue at all.  Your first post seems to have initiated that but, even after that, arguing hasn't been my intent.

I am confused by your comment though.  What popup?  How did that ever become part of this?  There was an alert but the last post removed it.  Any popup, even if it is blocked, is part of something else, not my code.  The page did work in IE 6 for me.

>> I am not answering questions here, I asked one. <<

You have to answer questions if you expect to get help.  To get an answer you will almost always have to interact with the experts by answering and responding to them.

The "working code" you posted doesn't seem to work for the second or third items you asked for.  Also that code is also used for the whole iinput value.  On its own it won't get a character or change it like in an onkeyup event.

I notice now that I did read the first part backwards.  Your use of toUpperCase() in your "solution" was what I should've suggested in my first post instead of toLowerCase().  Sorry about misreading that.  The correct figure numbers to use in my chkKeyLower function would be as follows if you want uppercase characters instead.

function chkKeyLower(e) {
      var k = (e.which)? e.which : e.keyCode;
      if (k < 65 || k > 90) {
            return false;
      }
      return true;
}

Of course the function name could be changed too if you change the html event as well.

This post is mainly for the Moderator if you are really not interested anymore.  I'll leave it to them to decide what is best for this.  If you do still need help and want to work with someone that can help then just let me know.

bol

 

by: simiPosted on 2007-10-17 at 20:32:42ID: 20098617

This is for the moderators.
Please delete this question.

And, if possible, advise how to deal with "experts" that won't let go.

:-)

 

by: b0lsc0ttPosted on 2007-10-18 at 14:12:54ID: 20104739

Vee_Mod - The CS question you linked is a different member than the Asker and seems to be a different question.  Just wanted to give you a heads up in case your notice was posted in the wrong question.  I do like the recommendation though and am not objecting to it.

bol

 

by: ee_ai_constructPosted on 2007-10-22 at 09:14:16ID: 20124265

Accepted by proxy.
ee_ai_construct
community support moderator
replacement part #xm34

 

by: simiPosted on 2007-10-22 at 09:41:26ID: 20124554

I have never accepted any solution.
On the opposite, I asked question to be deleted.
Not sure what exactly happened. I find this process very unclear.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...