user3674827
user3674827

Reputation: 21

Credit Card Number Validation

Hello I am having trouble with my javascript validation. I am trying to validate a credit card number which I want it to display between 13 and 18 numbers and single spaces.

My Javascript code:

<script type="text/javascript">
function validateForm()
{
var x=document.forms["checkout_details"]["creditcard"].value;
    if(x.length != 13 || x.length != 18)//if the length is not 13 or 18
    {
        alert("Please enter a valid credit card number");//display message to user;
        return false;
    }    
}
</script>

HTML/PHP Code:

echo '<form name="checkout_details" action="confirm.php" onsubmit="return validateForm()" method="post">';
echo '<font color="red">*</font>&nbsp;<b>Credit Card Number:</b> <input type="text" name="creditcard" id="creditcard"><br /><br />';
echo '<input type="submit" value="Purchase">';
echo '</form>';

Anyone help me out tell me what i'm doing wrong. Thanks.

Upvotes: 0

Views: 1568

Answers (6)

Ian Gibs
Ian Gibs

Reputation: 11

Validating credit cards is more than just the length of card number. To properly validate the card number (including the length), you should perform a check against the Luhn Algorithm. Use this code:

const options = {
  method: 'GET',
  headers: {Accept: 'application/json', 'X-Api-Key': '[APIkey]'}
};

fetch('https://api.epaytools.com/Tools/luhn?number=[CardNumber]&metaData=true', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

Upvotes: 1

0riginal
0riginal

Reputation: 137

Credit card validation is not that simple. You should use a regex to check it. There are also a large variety of credit card formats.

You can see the different regex' here Credit card regex'

Upvotes: 1

Federico Giust
Federico Giust

Reputation: 1793

Try this

if(x.length > 13 && x.length < 18) //if the length is between 13 and 18

There's also a very good plugin for CC validation here

jquery credit card validator

Upvotes: 0

RodrigoDela
RodrigoDela

Reputation: 1736

Shouldn't it be:

if(x.length < 13 || x.length > 18)

Upvotes: 0

You meant

if (x.length < 13 || x.length > 18) {
    ...
}

The original complains if the length is not exactly 13 and 18 characters; that is: always, as a string having length of 13 cannot have length of 18 and vice versa; also you want to match all the lengths in between.

Upvotes: 2

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

Instead of

if(x.length != 13 || x.length != 18)

you should use

if(x.length != 13 && x.length != 18)

in fact, with your original condition, 18 is different from 13, and that would have returned true!

Also, that accepts only exact length of 13 or 18, if you want to reject anything shorter than 13 or longer than 18, then you need

if(x.length < 13 || x.length > 18)

Upvotes: 2

Related Questions