Validating credit card expiration date
← ejemplos
FormValidation provides some built-in validators to validate a credit card information which include
- creditCard for credit card number validation
- cvv for CVV number validation
- stringCase for owner name validation
The question is that how to validate the expiration date which is often a required part in a payment form. Because the date validator asks for all the year, month and day, it isn't helpful in that case.
This example introduces some approaches to solve this problem.
Using two separated fields
Assume that you are using two separated fields for expiration date. The first field asks user to fill the expiration month, and the second one is for the expiration year.
We will use the callback validator to check the validity of month and year fields. Because these fields depend on each other, the updateStatus() method is used to set month/year field as valid one.
Supporting two digits year
The example above requires the expiration year to be a full four digits year. What if we need to support two digits year such as 18 instead of 2018?
The transformer option will be used in this case. The idea is that using this option to transform a two digits year number into a four digits year number:
Using one field
The second approach is applied when using one field for both expiration month and year. The valid format of the field is YYYY/MM.
We will use the regexp validator to determine if the input follows the required format first, and the callback validator to check whether or not it is expired by comparing with current date.