I have masked inputs for Phone, Fax, and Zip Code. Phone and Fax are formatted like (999) 999-9999 and the Zip Code is formatted like 99999-9999. When I submit the page, the the database is expecting a different format. When I update the database, I only need to pass in the number values. I need to convert the formats prior to passing them in to a SQL INSERT. How do I go about converting the format displayed on the page to the format required by the database?
The database is expecting Phone and Fax formats like: 1234567890
and Zip Code format like: 123456789 (although it doesn't require it to be all 9 digits as most people enter Zip Codes with only the first 5 numbers)
Although it doesn't convert the numbers correctly, here is a jsFiddle http://jsfiddle.net/HMG28/
I added a button on the jsFiddle which just appends the results in a div. On my real page that is a Submit button that posts the values so they can be accessed and passed in my INSERT statement. I'm not sure whether I should catch this and convert is using jQuery or in my PHP section. (PHP is what I think would be the correct way, just not sure how)
Here is a snippet of the code in the jsFiddle:
<label>Phone: </label><input type="text" id="phone" placeholder="(555) 555-5555" />
<label>Fax: </label><input type="text" id="fax" placeholder="(555) 555-5555" />
<label>Zip Code: </label><input type="text" id="zipcode" placeholder="Zip Code" />
$('#phone').mask('(999) 999-9999');
$('#fax').mask('(999) 999-9999');
$('#zipcode').mask('99999-9999');
On a side note, I do have names on the inputs so I can POST the values, I just didn't add it in this example.
Please let me know if there is any additional information needed.
The masked inputs make it nice for validating and UI. but the "meta" characters int he string can be easily removed (which is what your database looks like it needs). with that said, two variations:
PHP (preferred method, least possibility for user interaction):
// perform the cleanse server-side
$param = preg_replace('/([^d])/', '', $param);
JavaScript:
// perform the cleanse client-side
param = param.replace(/([^\d])/g,'');
Either way you'll be left with 1234567890
for a (123) 456-7890
phone number and 123456789
for a 12345-6789
zip. You may also want to (after stripping the other characters) run a test to make sure the length equals 10 and 9/5 for a phone and zip respectively. e.g.
// NOTE: i'm not checking `$_POST` but you should...
$phone = preg_replace('/([^\d])/', '', $_POST['phone']);
$fax = preg_replace('/([^\d])/', '', $_POST['fax']);
$zip = preg_replace('/([^\d])/', '', $_POST['zip']);
if (strlen($phone) == 10
&& strlen($fax) == 10
&& (strlen($fax) == 5 || strlen($fax) == 9)){
// proceed with inserting the three values in to the databasse;
// they are now clean and are of the proper lengths.
}