cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2 store views hyphen/dash recommended solution

SOLVED

Magento 2 store views hyphen/dash recommended solution

I'm not able to create store views with code/url like en-sa because of the backend validation:

The store code may contain only letters (a-z), numbers (0-9) or underscore (_), and the first character must be a letter.

What is the best solution/workaround for allowing dashes in store views without affecting Magento integrity, modules and third party plugins? Is it ok to change it directly in database table store?

 

Please help.

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Magento 2 store views hyphen/dash recommended solution

Override storecodevalidator function 

 

Defined below into global di.xml

<preference for="Magento\Store\Model\Validation\StoreCodeValidator"
type="Package\Module\Model\Validation\StoreCodeValidator"/>

 

Override isValid($value) function 

public function isValid($value)
{
$validator = $this->regexValidatorFactory->create(['pattern' => '/^[a-z]+[a-z0-9_\-]*$/i']);
$validator->setMessage(
__(
'The store code may contain only letters (a-z), numbers (0-9) or underscore (_),'
. ' and the first character must be a letter.'
),
\Zend_Validate_Regex::NOT_MATCH
);
$result = $validator->isValid($value);
$this->_messages = $validator->getMessages();

return $result;
}

 

Then after run setup:di:compile

 

That's all !!

View solution in original post

3 REPLIES 3

Re: Magento 2 store views hyphen/dash recommended solution

did you find a solution ?

Re: Magento 2 store views hyphen/dash recommended solution

Override storecodevalidator function 

 

Defined below into global di.xml

<preference for="Magento\Store\Model\Validation\StoreCodeValidator"
type="Package\Module\Model\Validation\StoreCodeValidator"/>

 

Override isValid($value) function 

public function isValid($value)
{
$validator = $this->regexValidatorFactory->create(['pattern' => '/^[a-z]+[a-z0-9_\-]*$/i']);
$validator->setMessage(
__(
'The store code may contain only letters (a-z), numbers (0-9) or underscore (_),'
. ' and the first character must be a letter.'
),
\Zend_Validate_Regex::NOT_MATCH
);
$result = $validator->isValid($value);
$this->_messages = $validator->getMessages();

return $result;
}

 

Then after run setup:di:compile

 

That's all !!

Re: Magento 2 store views hyphen/dash recommended solution

Google itself recommends that you use hyphens - instead of underscores _ in your URLs.

here is a reference from google web master central

Google Webmaster Central

 

Still not sure why Magento not allowing hyphens for store code.

You can try the given solution to allow hyphens to store code