google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank
Guest, register






Credit Card Numbers JavaScript Validating Tips and Codes This JavaScript article tutorial guides you a full completed instructions to validate a credit card number with JavaScript programming language, JavaScript RegEx. This post contains both detailed step by step guides and full JavaScript source codes for examples, please go to the inner post page for all.

Other JavaScript article tutorials from same author:
- Design Better HTML5 Form Element Validator
- JavaScript Date and Time Validating Tutorials


Label: credit card number validator, JavaScript validate credit card number, JavaScript RegEx

Free iPage Web Hosting for First Year NOW



If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?

Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Try iPage for FREE First Year NOW

It's still amazing to me that so many sites have no idea how to make a simple form usable. This article presents methods for validating credit card numbers and dates in a user-friendly fashion.

Validating Credit Card Numbers

Everyone knows that a credit card number is normally made up of 12-16 numbers. However there are many ways that people type their number into a form, often including spaces or hyphens to break up the number and make it more readable.

A lot of forms set the maxlength of the field to 16 characters which means that you can type most of your number - using spaces or dashes to separate blocks of numbers - before running out of space and having to go back and remove the spaces before entering the rest. Why?!?

Others will let you enter the number with extra characters, but then send you back an error message when the form is submitted. Again, why?!?

Let's see how we can do it better:

(eg. 4111-1111-1111-1111)

What have we done then?:

  • input length limited to 20 characters using maxlength;
  • you can type the number however you want - using spaces or dashes or other characters as separators;
  • when you exit the field (onBlur) any non-numeric characters are stripped out;
  • when you return to the field (onFocus) your formatted string is replaced.

To achieve all this extra functionality you just need to add the following to your page:

<script type="text/javascript">

  // initialise variable to save cc input string
  var cc_number_saved = "";

</script>

and this is the code for the relevant form field (comments can be removed):

<input type="text" size="24" maxlength="20" name="cc_number" onBlur="

  // save input string and strip out non-numbers
  cc_number_saved = this.value;
  this.value = this.value.replace(/[^\d]/g, '');
" onFocus="
  // restore saved string
  if(this.value != cc_number_saved) this.value = cc_number_saved;
">

When the form is submitted the credit card input will be numbers only which is handy for processing. You should always validate all form input using a server-side script to cater for non-JavaScript browsers or exploit attempts.

Checking for valid credit card numbers

This example goes one step futher and also checks that the number entered is valid according to the Luhn algorithm (also known as the "mod 10" algorithm).

(eg. 4111-1111-1111-1111)

This requires an extra JavaScript function that implements the Luhn algorithm:

function checkLuhn(input)
{
  var sum = 0;
  var numdigits = input.length;
  var parity = numdigits % 2;
  for(var i=0; i < numdigits; i++) {
    var digit = parseInt(input.charAt(i))
    if(i % 2 == parity) digit *= 2;
    if(digit > 9) digit -= 9;
    sum += digit;
  }
  return (sum % 10) == 0;
}

For the logic and history behind the algorithm see the link above. Basically it's a method used by credit card companies for decades now to detect errors in card numbers without having to look up the actual account.

We then make a small addition to the onBlur handler from the previous example:

<input type="text" size="24" maxlength="20" name="cc_number" onBlur="

  // save input string and strip out non-numbers
  cc_number_saved = this.value;
  this.value = this.value.replace(/[^\d]/g, '');
  if(!checkLuhn(this.value)) {
    alert('Sorry, that is not a valid number - please try again!');
    this.value = '';
  }
" onFocus="
  // restore saved string
  if(this.value != cc_number_saved) this.value = cc_number_saved;
">

You can test this with your own credit card number or, if you're a less trusting individual, the sample next to the input box will also pass the test. Or you can save the contents of this link to your computer and do the testing there:

[Stand-alone example]

Checking onSubmit instead of onChange

If you don't want to clutter up your form with all those JavaScript events then the same checks can be made in a checkForm function called when the form is submitted:

<script type="text/javascript">

function checkLuhn(input)
{
  ...
}

function checkForm(form)
{
  ...
  if(!checkLuhn(form.cc_number.value.replace(/[^\d]/g, ''))) {
    alert("You have not entered a valid Card number, please check and try again");
    form.cc_number.focus();
    return false;
  }
  ...
}


</script>

User-friendly Date Validation

Another sticking point with online forms is date validation. People get confused between dd/mm/yyyy and mm/dd/yyyy not to mention other formats. In desperation a lot of sites implement drop-down lists for days, months and years - adding more complexity to the form and the scripts that have to parse the data.

Let's see what we can come up with:

(dd/mm/yyyy)

What have we done?:

  • limted input to 10 characters using the maxlength attribute;
  • used the onKeyUp event to remove invalid characters as-you-type;
  • used the previously presented checkDate function to validate the format; and
  • if the format is correct, present the date in text format to the right of the input box.

The main advantage of this over the use of drop-down lists is that if the date entered does not exist, it's clear to the user. For example, entering 31/2/2004 will present a date string of 2 March 2004 which should alert the user that there's a problem.

Note: The actual format of the date presented to the user will vary across browsers and platforms. It should use the local 'Locale' settings of the computer but not all browsers do. Firefox 1.5 (Mac) in particular seems to always use mm/dd/yyyy format.

The code to achieve this is as follows (comments can be removed):

<input type="text" size="12" maxlength="10" name="start_date" onKeyUp="

  // allow only numbers and slashes
  this.value = this.value.replace(/[^\/\d]/g, '');
" onChange="
  if(checkDate(this) && document.getElementById) {
    // explode input and convert to Date object
    var parts = this.value.split('/');
    var testDate = new Date(parts[2], parts[1]-1, parts[0]);
    // update date string
    document.getElementById('confirm_start_date').innerHTML = '(' + testDate.toLocaleDateString() + ')';
  }
"> <small id="confirm_start_date">(dd/mm/yyyy)</small>

Note: To change the format to mm/dd/yyyy (US-format) just swap parts[0] and parts[1] in the above code.

The code for the checkDate function can be found in the article on Form Validation: Date and Time. In this example we've used a minYear of 1902 and a maxYear of the current year + 1.

The reason for using 1902 is that JavaScript on many platforms will not recognise dates earlier than 13 December, 1901 or after January 19, 2038 due to the binary equivalent of Y2K. See the link below to the Project 2038 FAQ for more details.

Why bother?

Some programmers are dismissive of client-side validation as it can't be used as a replacement for server-side validation and therefore creates more code to maintain. The reality is that some quite simple HTML, JavaScript or even Ajax code can make a big difference in terms of reducing the number of requests to the server and keeping your users happy.

The point of the above examples is to show how you can use a number of different techniques to filter form input. You can use the HTML maxlength attribute to restrict the number of input characters, filtering 'as you type' to limit or format input, and present 'feedback' to highlight where there might be problems before the form is submitted.

The key thing to keep in mind at all times is the user experience. If you're doing something to the input it should be obvious that it's happening and clear as to why it's being done.

Related Articles

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web