HTML Tutorial


 Forum HomeForum Home   FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 
RegisterRegister - Not registered yet? Got something to say? Join HTML Code Tutorial!
regular expression for digits 0-9
Post new topic   Reply to topic    HTML Help Forum Index -> PHP
View previous topic :: View next topic  
Author Message
raninda



Joined: 10 Apr 2008
Posts: 11

PostPosted: Mon Apr 14, 2008 5:14 pm     regular expression for digits 0-9 Reply with quote

i try to make regular expression.
user should only put digits 0-9 in textbox but i don't know how.
please help
kanenas



Joined: 14 Dec 2004
Posts: 191

PostPosted: Tue Apr 29, 2008 6:21 pm     /[0-9]/ Reply with quote

<boilerplate>Learn how to ask questions smartly. The guide may seem patronizing and is mostly common sense, but it will help you and others understand your problem. As it mentions, you get a certain amount of slack if you're not writing in your native language.</boilerplate>

There are many flavors of regular expressions. Check out Regular-Expressions.info for the lowdown. PHP (which I assume you're using, as this is the PHP forum), for example, supports 2 different flavors: POSIX Extended and Perl compatible (PCRE).

Every RE I can think of supports bracket character classes, '^' for beginning and '$' for end. /[0-9]/ will match any digit and /[^0-9]/ will match any non-digit character. /^[0-9]+$/ will match integers, including those with leading zeros (e.g '000'). Homework: write a regular expression (using [0-9]) to match fixed point numbers in base 10. It must be able to match positive and negative numbers, integers and floats without magnitude (digits before the decimal point), but doesn't need to match any form of scientific notation. Sample to match: '+0', '-2.35', '.618034'.

From a usability standpoint, by the time the user has submitted a form it's too late to correct input mistakes (which is when a PHP script will come into play). Better would be to hook the submit event for the form and alert the user after zhe has submitted the form but before the HTTP request is sent, but even this is a little late. Best is to use an input mask, which will prevent user from ever entering invalid characters. You'll still need the input validation server side, not for the user but for data integrity.

So how do you prevent a user from entering invalid data? The short version:

  • register an event handler for the 'keypress' event on the form field.
  • In the event handler:
    1. evaluate the pressed key in the context of what's already in the form field (in general, this is the hardest step).
    2. if valid, do nothing
    3. if invalid, display a warning and prevent the default event handler from running.

The code for the pressed key is stored in the event's keyCode or charCode property (which depends on the browser). Default event handler cancelation depends on how you register the event: for inline and traditional (e.g. via 'onkeypress' attribute), return 'false' from the event handler. For more modern methods (addEventListener and attachEvent), call the event's 'preventDefault' method (for all DOM2 compliant browsers) and assign false to 'returnValue' (for IE). If you want to cancel all remaining handlers for an event (and not just the default), call event's 'stopPropagation' method and assign false to event's 'cancelBubble' property. Here's a complete if somewhat simple client-side example using traditional event registration; a google search will turn up more general purpose examples. Be warned that not all script libraries are created equally.
Code:
<style type="text/css">
.hidden { display: none; }
.warning .bang {
  color: red;
  background-color: yellow;
}
</style>
<script type="text/javascript">
function unhideNode(node) {
    node.className = node.className.replace(/ hidden/g, '');
}
function unhideNodeById(id) {
  var node = document.getElementById(id);
  if (node) unhideNode(node);
}
function hideNodeById(id) {
  var node = document.getElementById(id);
  if (node) {
    node.className += " hidden";
  }
}

function isdigit(ch) {
    return /[0-9]/.test(ch);
}

function setMessage(node, msg) {
    node = node.lastChild;
    var msgNode = document.createTextNode(msg);
    if (node.firstChild)
        node.replaceChild(msgNode, node.firstChild);
    else
        node.appendChild(msgNode);
}

function warn(id, msg) {
    var node = document.getElementById(id);
    if (node) {
        setMessage(node, msg);
        unhideNode(node);
    }
}

function filter(event, isValid, warnID, warnMsg) {
  if (event.keyCode || event.charCode) {
    if (! isValid(String.fromCharCode(event.keyCode || event.charCode))) {
        warn(warnID, warnMsg);
        return false;
    }
  }
  return true;
}
</script>
...
<input id="" name="" onkeypress="return filter(event, isdigit, this.id+'_warn', 'Type only digits')"><span id="_warn" class="warning hidden"><span class="bang">!</span> <span class="message"></span></span>


Note that the use of inline event registration isn't the best approach, but it works in this example.
Display posts from previous:   
Post new topic   Reply to topic    HTML Help Forum Index -> PHP All times are GMT - 8 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
HTML Help Archive
Powered by phpBB © 2001, 2005 phpBB Group
HTML Help topic RSS feed 

 
HOSTING / DESIGN
MAKE MONEY

Home
  |   Tutorials   |   Forum   |   Quick List   |   Link Directory   |   About
Copyright ©1997-2002 Idocs and ©2002-2007 HTML Code Tutorial