Categories
Magento

How to Validate Input Field Value via Regex in Magento2

In this tutorial, We’ll learn how to validate input field value via regex in magento2. This validation is done on the server side via PHP and very effective. You can use this via ajax also.

Create a file anywhere from where you want to call this function and use below code:

<?php

namespace Vendor_Name\Module_Name\File_Path;

use InvalidArgumentException;

class InputValidator
{
    public function __construct(
        \Magento\Framework\Validator\RegexFactory $regexValidatorFactory
    ) {
        $this->regexValidatorFactory = $regexValidatorFactory;
    }

    public function checkInput(string $content)
    {
        if ($content) {
            $inputValidator = $this->regexValidatorFactory->create(
                [
                    'pattern' => '/^[A-Za-z0-9_.]+$/'
                ]
            );

            if (!$inputValidator->isValid($content)) {
                throw new InvalidArgumentException(
                    'Attribute name "%1" is invalid. Content should contain only characters, digits and dots', $content
                );
            }
        }
    }
}

Magento provides also inline pattern validation so you can use this also. Hope this server side code would be helpful. If you still have any issue feel free to ask and let me know your views to make the better. Share this solution with your other Magento buddies via social media.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *