问题
How to validate the credit card number based on credit card type. I am designing the form where I have two fields CreditCard type and Credit Card Number. How to validate the credit card number based on credit card type. I know about custom validator to apply on creditcardnumber field and validate from the regex, but when user change the credit card type then creditcardnumber validator will not call. I don't want to set validator on FormGroup level, because my form contains 50+ properties and that is the performance bottleneck(I believe). Is there any alternative way to achieve this.
Please help.
回答1:
You can simplify your stuff by using some npm packages, https://www.npmjs.com/package/ngx-credit-cards
回答2:
form the https://angular.io/guide/form-validation#note-on-performance:
By default, all validators are run after every form value change...We can delay updating the form validity by changing the updateOn property from change (default) to submit or blur
After this, you can change the validation using setValidators, applying only in changes of the cardType
this.form.get('cardType').valueChanges.subscribe(cardType=> {
switch (cardType)
{
case 1:
this.form.get('cardNumber').setValidators(.....);
break;
...
}
this.form.get('cardNumber').updateValueAndValidity();
});
Or make a customValidator that get two values (the cardType and the cardNumber)
customValidator2(params: any) {
return (control: AbstractControl) => {
let form=control.parent;
if (form)
{
let cardType=form.get('cardType').value;
let cardNumber=form.get('cardNumber').value;
switch (cardType)
{
case 1:
....
break;
}
return null;
}
}
Or make a customValidator at level of Form: https://angular.io/guide/form-validation#cross-field-validation
来源:https://stackoverflow.com/questions/52885776/credit-card-validation-in-angular-reactive-form