Update: a custom validation script that does not compile now fails the rule and shows the error, instead of letting every value through; the documentation explains the strict
true result and the empty-field case. Fixed in
WUIC Framework 1.8.2 .
The original answer below describes versions before 1.8.2.QuestionI added a script to the custom validation callback of a column. The rule seems correct, but the form refuses to save, or the check behaves oddly when the field is empty. What does the callback have to return, and when does it run?
AnswerThe callback must
explicitly return the boolean true when the value is valid. The framework tests the result with a strict comparison, so anything that is not exactly
true (no
return at all, a string, a number, a BehaviorSubject) counts as a failed validation.
The script is the body of an async function with the arguments
record, field, vr, wtoolbox.
record holds BehaviorSubjects, so you read a value with
.value. To show your own text, set
vr.message before returning
false.
Two behaviours that are easy to miss:
- Unlike the built-in format and length rules, the custom rule also runs when the field is empty. That is what makes "required only if another field is filled" possible, but it also means your code must cope with
null and empty strings. - If the script throws, the validation fails and the user sees an error dialog. If the script cannot be compiled, the rule is silently replaced by one that always returns
true, so check the browser console when a rule seems to do nothing.
A working example (the field is mandatory when
colonna_numero has a value):
const v = record[field.mc_nome_colonna].value;
if ((v === null || v === undefined || v === '') && record['colonna_numero'].value) {
vr.message = 'Required field';
return false;
}
return true;
A frequent mistake is returning the tested value itself, for example
return record.codice.value;. It is truthy but not
true, so the save is blocked. Return a comparison such as
return !!record.codice.value; or an explicit
true/
false.
Documentation: Callback & metadata cookbook Edited by user
10 days ago |
Reason: fixed in 1.8.2