Recently I had to modify the customer registration form from one of the websites I manage. VAT ID had to be included but only for professional customers. This meant that when a customer clicked on the «I’m a professional» field, new fields should show up and, the most important, the TAXVAT field had to become required (when in Magento is not required).

This solution is not perfect because it uses just the javascript validation. But this is fair enough for us. The important point I’m going to show you is how to make a field dynamically required or not by javascript in a Magento 2 form.

<form class="form create account form-create-account" action="<?= $block->escapeUrl($block->getPostActionUrl()) ?>" method="post" id="form-validate" enctype="multipart/form-data" autocomplete="off">
    <?= /* @noEscape */ $block->getBlockHtml('formkey'); ?>
    
    <fieldset class="fieldset create info">
        <legend class="legend"><span>Personal Information</span></legend><br>
        <input type="hidden" name="success_url" value="">
        <input type="hidden" name="error_url" value="">
        
        <div class="field field-name-firstname required">
            <label class="label" for="firstname">
                <span>First Name</span>
            </label>
 
            <div class="control">
                <input type="text" id="firstname" name="firstname" value="" title="First Name" class="input-text required" autocomplete="off" >
            </div>
        </div>
		<div class="field field-name-taxvat">
            <label class="label" for="taxvat">
                <span>First Name</span>
            </label>
 
            <div class="control">
                <input type="text" id="taxvat" name="taxvat" value="" title="taxvat" class="input-text" autocomplete="off" >
            </div>
        </div>
	</fieldset>
</form>

Magento initializes the form validation this way:

<script>
require([
    'jquery',
    'mage/mage'
], function($){
    var dataForm = $('#form-validate');
    dataForm.mage('validation', {});
});
</script>

If now we want to dynamically add a require validation for a specific field, we can use this:

$('#taxvat').attr('data-validate', '{required:true}'); // We add the required attribute necessary for the form validation
$('.field-name-taxvat').addClass('required'); // We add the require *


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.