customJS static method
Custom JavaScript validation.
Executes JavaScript code to validate the input value. The JavaScript code has access to:
input: the current field valuedata: entire form datavalid: boolean or string (error message)
Example:
FormioValidators.customJS(
'magic',
"valid = (input === 'magic') ? true : 'Must be magic';",
{},
)
Form.io format:
{
"validate": {
"custom": "valid = (input.length > 5) ? true : 'Too short';"
}
}
Implementation
static String? customJS(
String? value,
String jsCode,
Map<String, dynamic> formData, {
String? fieldName,
}) {
try {
// Import JavaScript evaluator
// ignore: implementation_imports
final jsEvaluator = _getJavaScriptEvaluator();
if (jsEvaluator == null) {
return 'JavaScript validation not available';
}
// Create JavaScript context
final context = {
'input': value,
'data': formData,
'valid': true,
};
// Validate code safety
jsEvaluator.validateCode(jsCode);
// Execute JavaScript
final result = jsEvaluator.evaluate(jsCode, context);
// Form.io validation result format:
// - true or 'true' means valid
// - string means error message
// - false or anything else means generic error
if (result == true || result == 'true' || result == 'True') {
return null; // Valid
} else if (result is String && result.isNotEmpty) {
return result; // Custom error message
} else {
return '${fieldName ?? "This field"} is invalid.';
}
} catch (e) {
debugPrint('Custom validation error for ${fieldName ?? "field"}: $e');
return 'Validation failed: ${e.toString()}';
}
}