2

How can i add validations for only alphabets in First name and Last name fields in Customer registration form?

1

Extend name.phtml file in your theme as below and add letters-only validation:-

app\design\frontend\VendorName\themename\Magento_Customer\templates\widget\name.phtml

First Name:-

<input type="text" id="<?= $block->escapeHtmlAttr($block->getFieldId('firstname')) ?>"
                   name="<?= $block->escapeHtmlAttr($block->getFieldName('firstname')) ?>"
                   value="<?= $block->escapeHtmlAttr($block->getObject()->getFirstname()) ?>"
                   title="<?= $block->escapeHtmlAttr($block->getStoreLabel('firstname')) ?>"
                   class="letters-only input-text <?= $block->escapeHtmlAttr($block->getAttributeValidationClass('firstname')) ?>" <?php if ($block->getAttributeValidationClass('firstname') == 'required-entry') echo ' data-validate="{required:true}"' ?>>

Last Name:-

<input type="text" id="<?= $block->escapeHtmlAttr($block->getFieldId('lastname')) ?>"
                   name="<?= $block->escapeHtmlAttr($block->getFieldName('lastname')) ?>"
                   value="<?= $block->escapeHtmlAttr($block->getObject()->getLastname()) ?>"
                   title="<?= $block->escapeHtmlAttr($block->getStoreLabel('lastname')) ?>"
                   class="letters-only input-text <?= $block->escapeHtmlAttr($block->getAttributeValidationClass('lastname')) ?>" <?php if ($block->getAttributeValidationClass('lastname') == 'required-entry') echo ' data-validate="{required:true}"' ?>>

Now letters-only validation only accept letter in first name and last name, not numeric value.

  • It's working! Thanks. – Khushbu Apr 19 at 6:31
  • 2
    This is a nice an simple way to do a client side validation, but if the user really wants to, he/she can bypass this client side validation and actually fill in whatever for the firstname and lastname. You need a server side validation also. Unfortunately, I don't know exactly where the customer data validation happens. I just wanted to point this up as it might help have this in mind – Marius Apr 19 at 6:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.