views:

59

answers:

2

I have a basic html form that adds some data to the page using PHP. I want to make this form field a "Price" field. My html is:

<input class="bids" name="comment" id="comment" tabindex="4" />

How can I fix this field so that users can't enter random letters, dollar signs, dashes, or other weird formats. I want the output to be whole dollars. Sorry I'm a complete programming moron. :)

+1  A: 

Use javascript with regex to only allow digits for the client side. You should also do a server side check using php & regex to make sure the post data only contains digits.

Here is a javascript function that checks to make sure that a particular field input contains only numbers.

function IsNumeric(numstr)
{
    if (numstr.match(/^\d+$/ ) ) {

        alert("Valid number");
    }
    else
    {
        alert("Only numeric values are allowed");
    }
}

Take a look at this javascript regex guide to help you.

Don't forget to do the PHP checking on the server side as well...

The PHP regex function would look something like:

preg_match('/[0-9]+/', $numstr);
Sev
Wow awesome. So I would wrap that function in script tags and put in my header? Then how would I tie it to my form submit? (sorry, total complete programming noob!)
RodeoRamsey
Yes, in the <head></head> section.
Sev
A: 

give the form the onsubmit event

<form blah ... onsubmit="return proof(this)">

your proof function does something like:

var proof = function(form){
    value = form.comment;
    var strReg = "^([0-9\.\-])";
    var regex = new RegExp(strReg);

    return(regex.test(value));
}
helle
Thanks! Where would I put the proof function? header? javacript? (sorry)
RodeoRamsey
header would be god. inner a <script> tag ;-)and give the user a hint, that something does not work well ... and for sure check on the server as well, because actually i am able to send your server JS evaluated values
helle