feat(input-iban): allow array for IsCountryIBAN validator

This commit is contained in:
jorenbroekema 2021-07-20 11:26:09 +02:00
parent 2abb04cddd
commit b292509ac1
4 changed files with 54 additions and 4 deletions

View file

@ -0,0 +1,5 @@
---
'@lion/input-iban': patch
---
Allow array for IsCountryIBAN, similar to IsNotCountryIBAN. This enables for example enforcing only Dutch and Belgian IBANs, which is a common use case for Dutch/Belgian financial institutions.

View file

@ -50,6 +50,30 @@ export const countryRestrictions = () => {
};
```
You can pass a single string value, or an array of strings.
The latter may be useful, for example if you only want to allow BeNeLux IBANs.
```js preview-story
export const countryRestrictionsMultiple = () => {
loadDefaultFeedbackMessages();
return html`
<lion-input-iban
.modelValue=${'DE89370400440532013000'}
.validators=${[new IsCountryIBAN(['BE', 'NL', 'LU'])]}
name="iban"
label="IBAN"
></lion-input-iban>
<br />
<small>Demo instructions: you can use:</small>
<ul>
<li><small>BE68 5390 0754 7034</small></li>
<li><small>NL20 INGB 0001 2345 67</small></li>
<li><small>LU28 0019 4006 4475 0000</small></li>
</ul>
`;
};
```
## Blacklisted Country
By default, we validate the input to ensure the IBAN is valid.

View file

@ -128,14 +128,21 @@ export class IsCountryIBAN extends IsIBAN {
* @returns {Boolean}
*/
execute(modelValue) {
let isInvalid = false;
const notIBAN = super.execute(modelValue);
if (modelValue.slice(0, 2) !== this.param.toUpperCase()) {
return true;
if (typeof this.param === 'string') {
if (String(modelValue.slice(0, 2)) !== this.param.toUpperCase()) {
isInvalid = true;
}
} else if (Array.isArray(this.param)) {
isInvalid = !this.param.some(
country => String(modelValue.slice(0, 2)) === country.toUpperCase(),
);
}
if (notIBAN) {
return true;
isInvalid = true;
}
return false;
return isInvalid;
}
/**

View file

@ -21,6 +21,20 @@ describe('IBAN validation', () => {
expect(deValidator.execute('NL17INGB0002822608')).to.be.true;
});
it('accepts an array for IsCountryIBAN to enforce IBANs from multiple countries', () => {
const nlValidator = new IsCountryIBAN(['NL', 'FR']);
const deValidator = new IsCountryIBAN(['DE', 'SK']);
expect(nlValidator.execute('NL17INGB0002822608')).to.be.false;
expect(nlValidator.execute('FR1420041010050500013M02606')).to.be.false;
expect(nlValidator.execute('DE89370400440532013000')).to.be.true;
expect(nlValidator.execute('SK3112000000198742637541')).to.be.true;
expect(deValidator.execute('NL17INGB0002822608')).to.be.true;
expect(deValidator.execute('FR1420041010050500013M02606')).to.be.true;
expect(deValidator.execute('DE89370400440532013000')).to.be.false;
expect(deValidator.execute('SK3112000000198742637541')).to.be.false;
});
it('provides IsNotCountryIBAN to prevent IBANs from specific countries', () => {
const nlValidator = new IsNotCountryIBAN('NL');
const deValidator = new IsNotCountryIBAN('DE');