You see I am trying to validate credit/debit card numbers but with spaces in every 3 or 4 numbers. Let's say I have this credit/debit card number that includes three spaces as delimiters:
// american express => patrón [4,6,5]
3400[]000000[]00009
// discover => patrón [4,4,4,4]
6011[]0000[]0000[]0004
// mastercard => patrón [4,4,4,4]
5500[]0000[]0000[]0004
// visa => patrón [4,4,4,4]
4111[]1111[]1111[]1111
// los corchetes son representaciónes de un espacio dependiendo del patrón asignado
I added some patterns in the form of an array, in the case of American Express the pattern is, the first 4 digits are separated with a space followed by the next 6 digits with a space followed by the last 5 digits.
In the case of Discover, MasterCard and Visa the pattern is every 4 digits separated by a space followed by the next 4 and so on until the last four digits are reached. As I show above.
The multiple regex only validates like this:
// american expresa
340000000000009
// discover
6011000000000004
// mastercard
5500 0000 0000 0004
// visa
4111111111111111
This function validates card numbers with spaces as delimiters between every 3 or 4 numbers, depending on the type of card. In this case, I validate 4 types of cards in a single regex, which are American Express, Discover, MasterCard and Visa.
function validCard(input) {
var valid;
var regex = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9][0-9])[0-9]{12})$/;
if (regex.test(input)) {
valid = true;
} else {
valid = false;
}
return valid;
}
var input = "4111 1111 1111 1111";
valid card(input); // return false
Also use the regex that @Ali recommended but add an or to validate the amex card digits
var regex = /^(?:(\d{4}\s?){4}|(\d{4,6}\s?){3})$/
We can do it by using {} for specific amounts:
[0-9]{15,16}
: Indicates a 15 or 16 digit number|
: Indicates "OR"()
: We use parentheses to group the following expression.[0-9]{4}\s
: 4 digits followed by space([0-9]{4}\s){3}
: 4 digits followed by space, 3 times[0-9]{3,4}
: Only 3 or 4 digits.And if you don't want to require that you always have spaces every 4 digits, that is, allow something like
0000 00000000000000
that, things become easierWhereupon we say (4 digits optionally followed by a space) 4 times.
Edition:
Before you edited your question you had a format that ended with 3 digits and now one that ends with 5 digits, if it doesn't matter where the space is, you can use the following:
\d
: Specifies a single digit like [0-9]\s?
: Optionally specifies a space(\d\s?)
: It is a digit that may or may not be followed by a space{15,16}
: There can only be 15 or 16 digits with space.If you are interested in validating that the spaces are in specific positions, try using this regular expression.
you have a demo here
So I would validate things like:
But not other malformed numbers like: