Required the field based on select option using jQuery Validation Engine library

27 Views Asked by At

The validationEngineLanguage function is to handle the custom requiredIf rule. It checks if the selected value is in the requiredValues array and ensures that the #desc field is not empty for the required values.

(function($) {
  // Add custom rule for required fields based on selected value
  $.fn.validationEngineLanguage = function() {
    $.validationEngineLanguage.allRules.requiredIf = {
      "func": function(field, rules, i, options) {
        const fieldValue = field.val();
        const selectedValue = $(options.allrules.requiredIf.selectorValue).val();

        const requiredValues = options.allrules.requiredIf.requiredValues;

        if (requiredValues.includes(selectedValue)) {
          return fieldValue.trim() !== '';
        }

        return true;
      },
      "alertText": "* Field is required for the selected value."
    };
  };

  // Example usage
  $(document).ready(function() {

    $("#myForm").validationEngine({
      custom_error_messages: {
        ".validate[requiredIf]": {
          "message": {
            "*": {
              "alertText": "* Field is required for the selected value."
            }
          }
        }
      },
      validationEventTrigger: "change"
    });

    $("#type").change(function() {
      $("#desc").validationEngine('validate');
    });

  });
})(jQuery);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jQuery-Validation-Engine/2.6.4/validationEngine.jquery.min.css" integrity="sha512-fvBUZJJBrJrzrFYM/EN2isPokoNnx331y30ZXIxRRlop1aq6rT6d8oY6WJVsiXZoso0dIZ2nbQjtGLi6Kkxr/Q==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-Validation-Engine/2.6.4/languages/jquery.validationEngine-en.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-Validation-Engine/2.6.4/jquery.validationEngine.min.js"></script>


<form id="myForm">
  <label for="type">Type:</label>
  <select id="type" class="validate[required]">
    <option value="">Select Type</option>
    <option value="AA">Type A</option>
    <option value="BB">Type B</option>
    <option value="CC">Type C</option>
    <option value="DD">Type D</option>
    <option value="XX">Type X</option>
  </select>
  <br><br>
  <label for="desc">Description:</label>
  <input type="text" id="desc" class="validate[requiredIf[AA,XX],maxSize[10]]" />
  <br><br>
  <input type="submit" value="Submit">
</form>

But it seems the rule doesn't work as expected. Any idea?

0

There are 0 best solutions below