google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Kiểm tra số thẻ tín dụng với JavaScript Bài viết này sẽ hướng dẫn bạn chi tiết cách thức để kiểm tra một số thẻ tín dụng nào đó có hợp lệ hay không bằng JavaScript. Bài viết này cung cấp hướng dẫn rất chi tiết cùng với mã nguồn JavaScript ví dụ mẫu rất hoàn chỉnh. Bạn vui lòng vào trang trong để xem thêm.

Các bài viết khác cùng tác giả:
- Tạo trình kiểm tra vùng nhập liệu tốt hơn với HTML
- Hướng dẫn kiểm tra định dạng ngày tháng hợp lệ với JavaScript


Nhãn: kiểm tra số thẻ tín dụng, thẻ tín dụng

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

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 theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web