I have 2 fields for Month (both fields type is number), first one is for "From Month" and second is "To Month".

enter image description here

I want to restrict user to enter the less no. of month in "To Month" field as comparison to "From Month".

Suppose, user enter 8(no. of month) in "From Month" field so he can not enter the no. of month less than 8 in "To Month" filed. if he entered a value in "To Month" field less than "From field" then a validation message (please enter the month greater than "From Month") should be display after clicking on the submit button.

$monthFrom = $this->getRequest()->getParam('month-from');
$monthTo = $this->getRequest()->getParam('month-to');

 <div id="monthfield" class="admin__field field">
                    <label class="label admin__field-label" for="period_from"><span><?= __('From') ?>:</span></label>
                    <div class="admin__field-control control">
                        <input id="monthfrom" min="1" max="12" class="input-text month-from admin__control-text required-entry" type="number" placeholder="<?php echo __('') ?>" value="<?php
                        if ($monthFrom) {
                            echo $monthFrom;
                        } else {
                            echo "1";
                        ?>" name="month-from" />
<div id="monthfield1" class="admin__field field">
                    <label class="label admin__field-label" for="period_to"><span><?= __('To') ?>:</span></label>
                    <div class="admin__field-control control">
                        <input id="monthto" min="1" max="12" class="input-text month-to admin__control-text required-entry month-validation" placeholder="<?php echo __('') ?>" type="number" value="<?php
                        if ($monthTo) {
                            echo $monthTo;
                        } else {
                            echo "12";
                        ?>" name="month-to" />

my script code is: (But it's not working)

<script type="text/javascript">
    ], function ($) {
        $.validator.addMethod('month-validation', function (value) {
                    var monthfrom = $("#monthfrom").val();
                    return value >= monthfrom;
                }, $.mage.__('Please enter Month greater than or equal to from Month'));

Please help, How can I create a custom validation method which work according to my needs.

Any help will be appreciated.

  • Have you used custom code in frontend form ?
    – Msquare
    Apr 10, 2020 at 16:18
  • @Msquare Yes I am using custom code but I have use this for backend here. Apr 13, 2020 at 5:16


Your Answer

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

Browse other questions tagged or ask your own question.