<?php
namespace Myfitmix\Customformvalidation\Observer;

class Saveaddress implements \Magento\Framework\Event\ObserverInterface
{
    /**
     * @var \Magento\Framework\App\RequestInterface
     */
    public $request;
    protected $messageManager;
    protected $_responseFactory;
    protected $_url;

    public function __construct(

        \Magento\Framework\App\RequestInterface $request,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Framework\App\Response\RedirectInterface $redirect
    ){

        $this->request = $request;
        $this->messageManager = $messageManager;
       $this->_responseFactory = $responseFactory;
       $this->_url = $url;
       $this->redirect = $redirect;
    }

    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {

       $customerAddress = $this->request->getPost();

       $custprefix = $customerAddress["prefix"];
       $custfirstname = $customerAddress["firstname"];
       $custlastname = $customerAddress["lastname"];
       $custcustom_street1 = $customerAddress["street"]['0'];
       $custcustom_street2 = $customerAddress["street"]['1'];
       $custcustom_street3 = $customerAddress["street"]['2'];
       $custcustom_city = $customerAddress["city"];
       $custcustom_phone = $customerAddress["telephone"];
       $custcustom_postcode = $customerAddress["postcode"];

       $regexforname = '/^[0-9@#$%<>"!`_~:;?\/\^\]&\[*}{)(+=]*$/';
        $regexcustom_street = '/^[@#$%<>"!`_~:;?\/\^\]&\[*}{)(=]*$/';
        $regexcustom_phone = "/^[0-9)(+-]+$/";
        $regexcustom_postcode = "/^[0-9]+$/";
        if (preg_match($regexforname, $custprefix) || preg_match($regexforname, $custfirstname) || preg_match($regexforname, $custlastname) || !preg_match($regexcustom_postcode, $custcustom_postcode) || preg_match($regexcustom_street, $custcustom_city) || !preg_match($regexcustom_phone, $custcustom_phone) || ($custcustom_street1 != null && preg_match($regexcustom_street, $custcustom_street1)) || ($custcustom_street2 != null && preg_match($regexcustom_street, $custcustom_street2)) || ($custcustom_street3 != null && preg_match($regexcustom_street, $custcustom_street3)))
        {
           $cartUrl = $this->redirect->getRefererUrl();
           $this->_responseFactory->create()->setRedirect($cartUrl)->sendResponse();
           exit;
        }

    }
}
