Validate Field Based On Another Field

Introduction

This article outlines how to conditionally make a field mandatory based on the value of another field within your form. Specifically, if a dropdown field labeled Type is set to With Evidence, an Attachment field becomes a mandatory upload.

To ensure proper form behavior based on user input, two distinct methods are available for making a field mandatory depending on another field's value. Below, we will explore each method, providing step-by-step guidance to implement them effectively in your Joget forms.

How does it work?

Method 1: using multiple sections and section visibility

This method leverages Section visibility to display and require the attachment field conditionally.

  1. Place the file upload element in its section within the form.
  2. Configure Section Visibility to only show when the dropdown value is With Evidence.
  3. Set the file upload's validator to mandatory to enforce the upload when the section is visible.

Method 2: using Bean Shell validation script

This method uses a Bean Shell Validator script directly within the file upload field, bypassing the need for separate sections based on visibility logic.

  1. Place the following sample script as a Bean Shell Validator in the File Upload field. The script dynamically validates the necessity of the file upload based on the dropdown selection.
    import java.util.Arrays;
    import org.joget.apps.app.service.AppUtil;
    import org.joget.apps.form.model.Element;
    import org.joget.apps.form.model.Form;
    import org.joget.apps.form.model.FormData;
    import org.joget.apps.form.service.FormUtil;
    
    public boolean validate(Element element, FormData formData, String[] fileUploadValues) {
        boolean result = true;
        
        // Get dropdown select box value
        String field1Id = "type";
        Form form = FormUtil.findRootForm(element);
        Element field1 = FormUtil.findElement(field1Id, form, formData);
      
        if (field1 != null) {
            // Get value of field 1
            String[] field1Values = FormUtil.getElementPropertyValues(field1, formData);
      
            if(field1Values[0].equalsIgnoreCase("With Evidence") && fileUploadValues[0].isEmpty()){
                String id = FormUtil.getElementParameterName(element);
                formData.addFormError(id, "Attachment is required when type is 'with evidence'");
                result = false;
            }
        } else {
            // Ignore if the dropdown does not exist
        }
      
        return result;
    }
      
    // Call validate method with injected variable
    return validate(element, formData, values);

Download sample app

Download the demo app for Validate Field Based On Another Field
Created by Julieth Last modified by Aadrian on Dec 13, 2024