2

I have a field on my form that is required if another field contains a certain value but otherwise is optional. I have set up a custom validator as follows:

document.formvalidator.setHandler('description', function(value) {
    if (comment_required)
        {
        return value.length;
        }
    else
        {
        return true;
        }

});

where "comment_required" is set according to whether or not the field is mandatory.

If I define the field with a class of "validate-description" (only) it is never validated. If I set a class of "required validate-description" (which is what the Joomla documentation says I should do) the it seems the "required" cuts in first, and the user is not allowed a blank field.

1
  • Welcome to JSE Dave. Please take our tour while you wait for feedback/support. Commented Jan 28, 2022 at 22:39

1 Answer 1

1

Being overly complicated! The solution was simple - the code that sets "comment_required" should add or remove the "required" class on the input field!

My code now reads as follows. The website is for storing photos in various galleries (birdlifephotography.org.au). The gallery is selected from a drop down list, and some galleries require the user to put in a comment. There is an array mandatory_comment which specifies if the comment is needed for a specific gallery.

comment_required=mandatory_comment[gallery_id];
s=$("#jform_description-lbl").html();

// Add or remove the "*" on the field label that Joomla uses to show the field is required

if (comment_required)
    {
    if (s.slice(-2)!=" *")
        {
        $("#jform_description-lbl").html(s+" *");
        }

// and then add the required class if not present

    if (!$("#jform_description").hasClass("required"))
        {
        $("#jform_description").addClass("required")
        }
    }
else

// opposite action if current gallery does not require this

    {
    if (s.slice(-2)==" *")
        {
        $("#jform_description-lbl").val(s.slice(-2));
        }
    if ($("#jform_description").hasClass("required"))
        {
        $("#jform_description").removeClass("required")
        }
    }
1
  • Excellent job in resolving your problem and posting an answer. Are you able to expand on exactly how you implemented this fix? Providing a short snippet may help future researchers to better grasp how to solve this problem in their own application if you demonstrate how you did it. Commented Jan 30, 2022 at 21:24

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.