Reputation: 15
I am trying to validate credit card number from a string. It is working when i ONLY pass in the credit card number without anything else. But when there is just one other character it is not valid. I want to get the number from a string with other characters. Why?
Works (Only number)
var data = '4283023337565974'
if (/^(?:4[0-9]{12}(?:[0-9]{3})?)$/.test(data) === true) {
console.log('Valid Credit Card');
} else {
console.log('Invalid Credit Card');
}
Doesn't work (With other characters)
var data = '123abc4283023337565974def456'
if (/^(?:4[0-9]{12}(?:[0-9]{3})?)$/.test(data) === true) {
console.log('Valid Credit Card');
} else {
console.log('Invalid Credit Card');
}
Upvotes: 0
Views: 133
Reputation: 5055
Remove the ^
and $
characters from your Regex - They match for the Start and End of the String respectively
let data = 'abc4283023337565974def'
if (/(?:4[0-9]{12}(?:[0-9]{3})?)/.test(data) === true) {
console.log('Valid Credit Card');
} else {
console.log('Invalid Credit Card');
}
Alternatively, you could use .replace(/\D/g, '')
to remove any non-digit Character from your String beforehand
The Regex \D
matches any non-digit character, and g
is the global flag so it will find and replace all matches
let data = 'abc4283023337565974def'
data = data.replace(/\D/g, '');
if (/^(?:4[0-9]{12}(?:[0-9]{3})?)$/.test(data) === true) {
console.log('Valid Credit Card');
} else {
console.log('Invalid Credit Card');
}
Upvotes: 3