Validator to validate GTIN numbers.
An UPC number is equal to a GTIN-12 number, EAN or GLN are GTIN-13 numbers and can be validated using the corresponding size.
composer require dmt-software/gtin-validator
use DMT\GTIN\Validator\GTIN;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class Product
{
#[GTIN(size: 13, message: 'Invalid EAN code.')]
public string $ean;
}
$product = new Product();
$product->ean = '49923315534218';
/** @var ValidatorInterface $validator */
$errors = $validator->validate($product);
if (count($errors) > 0) {
foreach ($errors as $error) {
echo $error->getMessage() . ' ' . $error->getCause();
}
}
// prints: Invalid EAN code. Number length is not correct.