Stock validation in Multi-source inventory is needed when you developing functionality with MSI of Magento 2.
Stock Validation in MSI using native interface class.
Magento\InventoryApi\Model\StockValidatorInterface
StockValidatorInterface has method called validate(StockInterface $stock);
If you want to validate the Stock of MSI, You just need to implement StockValidatorInterface in your class.
You can validate Stock related information for your requirements.
A simple example for a Stock name is valid or not using StockValidatorInterface.
<?php
namespace Jesadiya\Inventory\Model\Stock\Validator;
use Magento\Framework\Validation\ValidationResult;
use Magento\Framework\Validation\ValidationResultFactory;
use Magento\InventoryApi\Api\Data\StockInterface;
use Magento\InventoryApi\Model\StockValidatorInterface;
/**
* Check that name is valid
*/
class NameValidator implements StockValidatorInterface
{
/**
* @var ValidationResultFactory
*/
private $validationResultFactory;
/**
* @param ValidationResultFactory $validationResultFactory
*/
public function __construct(ValidationResultFactory $validationResultFactory)
{
$this->validationResultFactory = $validationResultFactory;
}
/**
* @param StockInterface $stock
* @return ValidationResult
*/
public function validate(StockInterface $stock): ValidationResult
{
$value = (string)$stock->getName();
if ('' === trim($value)) {
$errors[] = __('"%field" can not be empty.', ['field' => StockInterface::NAME]);
} else if ('Default Stock' === trim($value)) {
$errors[] = __('"%field" is not allowed.', ['field' => StockInterface::NAME]);
} else {
$errors = [];
}
return $this->validationResultFactory->create(['errors' => $errors]);
}
}
Using the above code, You can validate your Stock with custom validation. In the validate method, You need to pass StockInterface Object as a parameter.
In the above code snippet, Validate the Stock is not empty and the Stock name does not equal to Default Stock.
When you Developing any functionality, You can set your custom validation for Stock data