Reputation: 67
i have written following jquery/javascript function for validating a credit card which is 15 digit long & must start with digit1. so, how would i validate that the number will start with digit 1.
if ($("#ddlCreditCardType" + i).val() == 'TP') {
if (!($("#txtCreditCardNo" + i).val().length == 15)) {
$("#err" + i).html('Credit Card Number should be 15 digit');
status = 0;
}
else {
$("#err" + i).html('');
status = 1;
}
Upvotes: 0
Views: 209
Reputation: 1473
It is recommended to user regular expression to validate the credit card. Check this expression:
^1[0-9]{14}$
The description:
Options: case insensitive; ^ and $ match at line breaks
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the character “1” literally «1»
Match a single character in the range between “0” and “9” «[0-9]{14}»
Exactly 14 times «{14}»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
Example usage:
var credit = "123456789123456"; // lingth 15
alert(credit.match(/^1[0-9]{14}$/)); // will success
credit = "1234567891234567"; // lingth 16
alert(credit.match(/^1[0-9]{14}$/)); // will fail
credit = "5234567891234567"; // lingth 15, start with 5
alert(credit.match(/^1[0-9]{14}$/)); // will fail
Upvotes: 0
Reputation: 179
You can use regex also.
var c1='123456789012345';
var c2='234567890123456';
var regex=/^1\d{14}/; //regular expressions starting with '1' and the 14 digits at the end
regex.exec(c1); //returns the c1
regex.exec(c2); //returns null
Upvotes: 0
Reputation: 21762
If you have to only support the most modern of browsers, you can do the following
var ccNum = $("#txtCreditCardNo" + i).val();
if(ccNum.startsWith('1')){
//Do something cause it starts with 1
}
If you have to support older browsers, you could do the following, which works in newer and older browsers:
var ccNum = $("#txtCreditCardNo" + i).val();
if(ccNum.split('')[0] == '1'){
//Do something cause it starts with 1
}
There are other options, but either of these would work.
Upvotes: 0
Reputation: 222
Use charAt function of JavaScript which allows you to read first character.
So in your code you can write:
if ($("#txtCreditCardNo" + i).val().charAt(0) == '1'){
// your code after validation
}
Upvotes: 0
Reputation: 1038850
You could take the first letter of the value and compare it with 1
:
if ($("#ddlCreditCardType" + i).val() == 'TP') {
var value = $("#txtCreditCardNo" + i).val();
if (value.length !== 15 || value[0] !== '1') {
$("#err" + i).html('Credit Card Number should be 15 digit and start with 1');
status = 0;
}
}
Upvotes: 2