Issue
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> <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.
Solution
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)
Answered By - Matteo Tassinari
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.