LoginSignup
1
1

More than 3 years have passed since last update.

Magento2でユーザーの住所入力を英語入力に制限(バリデーション)する

Last updated at Posted at 2020-02-12

越境ECをMagento2で作った場合に、テキスト部分の住所入力まで現地の言語で入力すると国際郵便などで配送する場合にオペレーションで英語に変換する必要があり大変ということで、ユーザーが住所入力する時点で英語でしか入力できないようにバリデーションをかけたい。

customer_eav_attributeにvalidation_ruleを追加する

Magento2のユーザーに関する属性の設定については customer_eav_attributeというテーブルに入っている。
customer_eav_attributeのvalidation_ruleというカラムにその属性のバリデーションルールについてJSONで設定をいれる。

以下のクエリを実行するとユーザーの住所に関する属性の、attribute_id,attribute_code、validation_ruleが一覧で見れる。

sql
SELECT 
customer_eav_attribute.attribute_id,
eav_attribute.attribute_code,
customer_eav_attribute.validate_rules
FROM customer_eav_attribute
JOIN eav_attribute ON customer_eav_attribute.attribute_id = eav_attribute.attribute_id
WHERE eav_attribute.entity_type_id = 2;

Screen Shot 2020-02-12 at 21.15.12.png

上記のfirstnameの属性のようにvalidation_rulesに "input_validation":"alpha" を追加するとアルファベット入力のみ制限できます。

json
{"input_validation":"alpha","max_text_length":25,"min_text_length":1}

正規表現を使って任意のパターンでバリデーションをかけたい場合は "pattern":"正規表現"を書く。
このとき、"正規表現"の部分はJSの new RegExp()に引数として与える文字列であり、かつJSONのフォーマットとしても正しくなるように書かないといけないので注意。
:json
{"pattern":"^[a-zA-Z0-9\\s\\-]+$","max_text_length":25,"min_text_length":1}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1