EANService: more idiot-proof input validation

This commit is contained in:
Lauren Liberda 2021-07-25 18:07:24 +02:00
parent 9ddfb7eef5
commit 7788a67a09

View file

@ -18,10 +18,14 @@ export class EANService {
} }
isValid(ean: string) { isValid(ean: string) {
ean = ean.trim();
assert(/^\d{13}$/.test(ean));
return this.calcChecksum(ean.slice(0, 12)) === parseInt(ean[12], 10); return this.calcChecksum(ean.slice(0, 12)) === parseInt(ean[12], 10);
} }
toID(ean: string) { toID(ean: string) {
ean = ean.trim();
assert(/^\d{12,13}$/.test(ean));
if (ean.length === 12) { if (ean.length === 12) {
// it already is an ID // it already is an ID
return ean; return ean;
@ -33,7 +37,8 @@ export class EANService {
} }
fromID(id: string) { fromID(id: string) {
assert(id.length === 12); id = id.trim();
assert(/^\d{12}$/.test(id));
return id + this.calcChecksum(id); return id + this.calcChecksum(id);
} }
} }