Converting Phone Numbers, Fax Numbers, and Zip Codes for Input into a Database

I'm facing an issue with masked inputs for Phone, Fax, and Zip Code on my webpage. The Phone and Fax numbers are currently formatted as (999) 999-9999, while the Zip Code is in the format 99999-9999. However, when I submit the page, the database requires a different format for these fields. Specifically, Phone and Fax should be in the format 1234567890, and the Zip Code should be in the format 123456789 (although it doesn't need to include all 9 digits).

I need to convert these formats before passing them into an SQL INSERT statement. How can I achieve this conversion from the displayed format on the webpage to the required format by the database?

Here is a jsFiddle that demonstrates the issue. It includes a button that appends results in a div, similar to how the actual Submit button functions on my page.

Currently, the code snippet in the jsFiddle looks like this:

<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');

Although I have names assigned to the inputs for POSTing values, I omitted them in this example for simplicity. Should I handle the conversion using jQuery or PHP? I believe PHP might be more suitable, but I am unsure about the implementation.

If you require any additional information, please feel free to ask.

Answer №1

Using masked inputs can be helpful for validation and user interface, but it's important to remove any "meta" characters in the string (which seems necessary for your database). Here are two different approaches:

In PHP (recommended method with minimal user interaction):

// Perform server-side cleansing
$param = preg_replace('/([^d])/', '', $param);

In JavaScript:

// Perform client-side cleansing
param = param.replace(/([^\d])/g,'');

After removing other characters, you will end up with 1234567890 for a phone number like (123) 456-7890, and 123456789 for a zip code like 12345-6789. You may also want to check that the length equals 10 for phones and 9 or 5 for zips after the cleansing process. For example:

// Note: I am not checking `$_POST` here, 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 cleaned values into the database;
  // they are now sanitized and of correct lengths.
}

Updated Fiddle Link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

"Troubleshooting: Why isn't my Bootstrap alert displaying properly after implementing Ajax

I'm currently working on validating a form using ajax. I have utilized bootstrap's alert alert-danger and alert alert-success classes to enhance the UI, but upon return, it is only displaying as plain HTML without the desired appearance. Can some ...

Encountering an issue trying to insert multiple objects into a Laravel session

Whenever I attempt to add an item to the cart, it only adds it once. If I try to do it again, it ends up overwriting the existing item and the counter for the items in the cart remains at 1. I've experimented with switching between a button and a lin ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

Removing all table rows except one in Jquery

I currently have this code in my view: <script> $(document).ready(function() { $("#add_instruction").click(function(){ $("#instructions").append("<tr><td></td><td><input type='text' name='rec ...

Retrieve the ID of the nearest div without it being executed twice

I am currently working on implementing a close button using 'onclick' functionality. The goal is to hide the parent ID element when the user clicks the button, as shown below. function displayNone() { var id= $('.btnClose').closest ...

Resolving the Encoding Problem While Transmitting PHP Data to a Textarea

I have implemented a functionality on my website that involves using two textareas and a button. The purpose is that when the button is clicked, all the information from textarea1 is sent to a PHP function which then reverses it and returns the result in t ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Retrieve a targeted tag from the API snippet

I need to extract the IMG SRC tag from the given code: <pod title="Scientific name" scanner="Data" id="ScientificName:SpeciesData" position="200" error="false" numsubpods="1"> <subpod title=""> <plaintext>Canis lupus familiaris</plain ...

Clicking on "li" to activate and deactivate

Currently utilizing: $('#btnEmpresarial').attr('onclick','').unbind('click'); In order to deactivate a read using javascript.. However, I now require enabling the onclick after the function has completed. Is ther ...

Shade of a row within a PHP table

I have a table that is populated with data from a database. Is there a way for me to dynamically change the color of a row based on certain conditions from a JSON file? For example, if the temperature exceeds a set minimum value, I want to highlight the ro ...

Creating an HTML form that submits data to a PHP script, which then saves the

Looking for some assistance with a PHP issue I am having. I know my way around PHP, but I wouldn't say I'm an expert. Here's the problem: I have created an HTML form (form.html) and now I want the output from formular.php to be saved as a u ...

Is it okay to have a foreach loop that includes PHP files multiple times?

I have implemented a function called "processMessage($msg)" which processes a string based on its prefixes, or the first few words in it. When fetching multiple rows from the database, I pass each $msg string through this function... The unique aspect he ...

PHP Calculator with Dynamic Calculations

I need to create an order form that updates the tax and total automatically once a quantity is entered into the text box. Should I use PHP or JavaScript for this functionality? Let's assume, for instance, that the tax rate is 0.3% My requirements: ...

Design Inquiry: Ways to Display Online User Count?

Currently in the process of creating a LAMP web application. I'm looking for effective strategies to showcase the number of users who are currently logged into my site. My goal is to provide accurate real-time information such as "There are 1000 users ...

managing website pages with a PHP curl script following authentication

I'm having trouble posting values to a field and completing the necessary steps to download a file. Can anyone provide insight into where I might be making a mistake? extract($_POST); $url=header("Location: http://gis.lntecc.com/bwssblnt/ ...

Easiest method to change cursor to 'wait' and then return all elements to their original state

On my website, there are certain CSS classes that define a specific cursor style when hovered over. I am trying to implement a feature where the cursor changes to a "wait" image whenever an AJAX call is initiated on any part of the page, and then reverts b ...

Unable to verify identity using spa

My API is running on the URL: https://example.com, and my vue.js app is running on: https://app.example.com. I have configured the .env file as follows: SESSION_DOMAIN=.example.com SANCTUM_STATEFUL_DOMAINS=https://app.example.com The axios configuration i ...