Magento 2.1 Forms – Understanding the Form Key

form-keyformsmagento-2.1

if (!$this->_validateFormKey()) {
  // do something
}

Any Magento 1 equivalent in Mangento 2 for _validateFormKey function.

And Can anyone explain how and where Magento checks formkey, when any form is submitted.

Basically I am not able to validate the formkey in controller, My form is submitted even if change the formkey value from inspect element.

Best Answer

Try following way:


protected $formKeyValidator;

public function __construct (
    \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
) {
    $this->formKeyValidator = $formKeyValidator;
}

And then


if (!$this->formKeyValidator->validate($this->getRequest())) {
    // invalid request
}