1

I need to change the "date of birth" field from date picker to three fields with validation.

How to do it?

1 Answer 1

0

modified the below files replace full code in dob.phtml

<?php 
         $dob=$block->getDate();
         $year='';
         $smonth='';
         $day='';
         if($dob){
         $dateofbirth = explode("-", $dob);
         $year=$dateofbirth[0];
         $smonth=$dateofbirth[1];
         $day=$dateofbirth[2];
       }
?>


<div class="field dob customer-dob">
            <label for="dob" class="label"><span><?php /* @escapeNotVerified */ echo __('Date of birth') ?></span>
            <span class="optional"><?php /* @escapeNotVerified */ echo __('(optional)') ?></span>
            </label>
            <div class="control">
            <input type="hidden" class="" value="<?php echo $dob; ?>" id="dob" name="dob" autocomplete="off">
            <input type="text"  value="<?php echo $day; ?>" name="date" id="dob_dd" title="<?php /* @escapeNotVerified */ echo __('dd') ?>" class="input-text validate-cdobd" placeholder="DD" style="width:20%"   maxlength="2" 
            onkeyup="moveOnMax(this,document.getElementById('dob_mm'))"/>

                <select id="dob_mm" name="month" title="<?php /* @escapeNotVerified */ echo __('mm') ?>"   style="width:20%;" class="select validate-cdobm">
                 <option value=""><?php /* @escapeNotVerified */ echo __('MM') ?></option>
                <?php for($month=1;$month<=12;$month++):?>
                    <option value="<?php /* @escapeNotVerified */ echo __($month) ?>" <?php if ($month == $smonth) echo ' selected="selected"' ?> ><?php /* @escapeNotVerified */ echo __($month) ?></option>
                    <?php endfor; ?>
                </select>

                <input type="text" maxlength="4" value="<?php echo $year; ?>"name="year" id="dob_yy" title="<?php /* @escapeNotVerified */ echo __('yy') ?>" class="validate-cdoby" placeholder="YYYY" style="width:20%" onkeyup="moveOnMax(this,document.getElementById('gender'))"/>
                <div class="validate-custom"></div>
            </div>
            <div class="clearboth"></div>
        </div>

        <script type="text/javascript">

function moveOnMax(field, nextFieldID) { 
    if (field.value.length >= field.maxLength) { nextFieldID.focus(); } 
}

</script>

in edit.phtml add below script in the end of the file

<script type="text/javascript">
    require([
        'jquery', // jquery Library
        'jquery/ui', // Jquery UI Library
        'jquery/validate', // Jquery Validation Library
        'mage/translate' // Magento text translate (Validation message translte as per language)
    ], function($){     

      var dataForm = $('#form-validate');
        var ignore = <?php echo $_dob->isEnabled() ? '\'input[id$="full"]\'' : 'null'; ?>;

        dataForm.mage('validation', {
        <?php if ($_dob->isEnabled()): ?>
            errorPlacement: function(error, element) {
                if (element.prop('id').search('dob_dd') !== -1 || element.prop('id').search('dob_mm') !== -1 || element.prop('id').search('dob_yy') !== -1) {
                  var dobElement = $(element).parents('.customer-dob'),
                        errorClass = error.prop('class');
                    error.insertAfter($('.validate-custom'));
                }
                else {
                    error.insertAfter(element);
                }
            },
            ignore: ':hidden:not(' + ignore + ')'
        <?php else: ?>
            ignore: ignore ? ':hidden:not(' + ignore + ')' : ':hidden'
        <?php endif ?>
        });


         $.validator.addMethod(
        'validate-cdobd', function(value) {
            var postToRahaha = $("#dob_yy").val();
             var dayVal = $("#dob_dd").val(),
                    monthVal = $("#dob_mm").val(),
                    yearVal = $("#dob_yy").val(),
                    dobLength = dayVal.length + monthVal.length + yearVal.length;
                /* if (params[3] && dobLength === 0) {
                    this.dobErrorMessage = 'This is a required field.';
                    return false;
                }*/
                if (dobLength=== 0) {
                    return true;
                } 
                var day = parseInt(dayVal, 10) || 0,
                    month = parseInt(monthVal, 10) || 0,
                    year = parseInt(yearVal, 10) || 0,
                    curYear = (new Date()).getFullYear();
                if (!day) {
                    this.dobErrorMessage = 'Please enter a valid full date.';
                    return false;
                }

                var validateDayInMonth = new Date(year, month, 0).getDate();
                if (day < 1 || day > validateDayInMonth) {
                    var validDateMessage = $.mage.__('Please enter a valid day (1-%1).');
                    this.dobErrorMessage = validDateMessage.replace('%1', validateDayInMonth.toString());
                    return false;
                }
                var today = new Date(),
                    dateEntered = new Date();
                dateEntered.setFullYear(year, month - 1, day);
                if (dateEntered > today) {
                    this.dobErrorMessage = $.mage.__('Please enter a date from the past.');
                    return false;
                }


                return true;
        },
            function () {
                return this.dobErrorMessage;
            }
        );

         $.validator.addMethod(
        'validate-cdobm', function(value) {
            var postToRahaha = $("#dob_yy").val();
             var dayVal = $("#dob_dd").val(),
                    monthVal = $("#dob_mm").val(),
                    yearVal = $("#dob_yy").val(),
                    dobLength = dayVal.length + monthVal.length + yearVal.length;
                /* if (params[3] && dobLength === 0) {
                    this.dobErrorMessage = 'This is a required field.';
                    return false;
                }*/
                if (dobLength=== 0) {
                    return true;
                } 
                var day = parseInt(dayVal, 10) || 0,
                    month = parseInt(monthVal, 10) || 0,
                    year = parseInt(yearVal, 10) || 0,
                    curYear = (new Date()).getFullYear();

                if (month < 1 || month > 12) {
                    this.dobErrorMessage = 'Please select a valid month.';
                    return false;
                }


                return true;
        },
            function () {
                return this.dobErrorMessage;
            }
        );

         $.validator.addMethod(
        'validate-cdoby', function(value) {
            var postToRahaha = $("#dob_yy").val();
             var dayVal = $("#dob_dd").val(),
                    monthVal = $("#dob_mm").val(),
                    yearVal = $("#dob_yy").val(),
                    dobLength = dayVal.length + monthVal.length + yearVal.length;
                /* if (params[3] && dobLength === 0) {
                    this.dobErrorMessage = 'This is a required field.';
                    return false;
                }*/
                if (dobLength=== 0) {
                    return true;
                } 
                var day = parseInt(dayVal, 10) || 0,
                    month = parseInt(monthVal, 10) || 0,
                    year = parseInt(yearVal, 10) || 0,
                    curYear = (new Date()).getFullYear();


                var today = new Date(),
                    dateEntered = new Date();
                dateEntered.setFullYear(year, month - 1, day);
                if (!(dateEntered > today)){
                    if (year < 1900 || year > curYear) {
                        var validYearMessage = $.mage.__('Please enter a valid year (1900-%1).');
                        this.dobErrorMessage = validYearMessage.replace('%1', curYear.toString());
                        return false;
                    }
                }

                day = day % 10 === day ? '0' + day : day;
                month = month % 10 === month ? '0' + month : month;
                $('#dob').val(month + '/' + day + '/' + year);
                return true;
        },
            function () {
                return this.dobErrorMessage;
            }
        );


    });
    </script>

make sure dob attribute enable from admin :-)

3
  • Where is dob.phtml and edit.phtml Apr 9, 2020 at 11:23
  • please get back to me magento\module-customer\view\frontend\templates\form\edit.phtml magento\module-customer\view\frontend\templates\widget\dob.phtml Apr 9, 2020 at 11:29
  • Facing error while click on create account ValueError: bcsub(): Argument #1 ($num1) is not well-formed in /var/www/html/magento2/vendor/magento/zendframework1/library/Zend/Locale/Math.php:259 Stack trace: #0 /var/www/html/magento2/vendor/magento/zendframework1/library/Zend/Locale/Math.php(259): bcsub() Apr 10, 2023 at 7:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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