使用BeanShell作为表单验证器

注入变量:

    • element - org.joget.apps.form.model.Element
    • values - java.lang.String[]
    • formData - org.joget.apps.form.model.FormData

返回值:

    • (true/false)。

例子:

将提交的值与另一个字段的值进行比较。

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[] values) {
    boolean result = true;
 
    //get field 1 value from form data object
    String field1Id = "field1";
    Form form = FormUtil.findRootForm(element);
    Element field1 = FormUtil.findElement(field1Id, form, formData);
 
    if (field1 != null) {
        //get value of field 1
        String[] compareValues = FormUtil.getElementPropertyValues(field1, formData);
 
        //compare the value of field 2 and field 1 are equals
        if (!Arrays.equals(values, compareValues)) {
            String id = FormUtil.getElementParameterName(element);
            formData.addFormError(id, "Value not equal!!!!");
            result = false;
        }
    } else {
        //ignore if the field 1 not exist
    }
 
    return result;
}
 
//call validate method with injected variable
return validate(element, formData, values);

使用BeanShell作为表单多行验证器

注入变量:

    • element - org.joget.apps.form.model.Element
    • rows - org.joget.apps.form.model.FormRowSet
    • formData - org.joget.apps.form.model.FormData

返回值:

    • (true/false)。

例子:

验证某列值的总和是否小于1000。

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.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.apps.form.service.FormUtil;
  
public boolean validate(Element element, FormRowSet rows, FormData formData) {
    boolean result = true;
    if (rows != null && !rows.isEmpty()) {
        int total = 0;
         
        //Sum the values from column "amount"
        for (FormRow row : rows) {
            try {
                int amount = Integer.parseInt(row.getProperty("amount"));
                total += amount;
            } catch (Exception e) {}
        }
         
        //if amount larger than 1000
        if (total > 1000) {
            String id = FormUtil.getElementParameterName(element);
            formData.addFormError(id, "Total amount should not larger than 1000!!!!");
            result = false;
        }
    }
  
    return result;
}
  
//call validate method with injected variable
return validate(element, rows, formData);
  • No labels