validateSurveyAnswers function
ValidationErrors
validateSurveyAnswers(
- AnswerValues answerValues,
- List<
Question> questions, - String locale
Implementation
ValidationErrors validateSurveyAnswers(
AnswerValues answerValues,
List<Question> questions,
String locale,
) {
final errors = <int, String>{};
for (final question in questions) {
final questionId = question.id;
if (questionId == null) continue;
final answer = answerValues[questionId];
if (question.isRequired) {
if (answer == null ||
(answer is String && answer.trim().isEmpty) ||
(answer is List && answer.isEmpty)) {
errors[questionId] = FormContentMessages.requiredQuestion(locale);
continue;
}
}
if (question.type.usesImageUpload) {
final files = answer is List<String>
? answer
: answer is List
? answer.whereType<String>().toList()
: const <String>[];
if (question.minSelected != null &&
files.length < question.minSelected!) {
errors[questionId] = FormContentMessages.minChoices(
locale,
question.minSelected!,
);
continue;
}
if (question.maxSelected != null &&
files.length > question.maxSelected!) {
errors[questionId] = FormContentMessages.maxChoices(
locale,
question.maxSelected!,
);
continue;
}
continue;
}
if (answer is String && answer.trim().isNotEmpty) {
final length = answer.trim().length;
if (question.minLength != null && length < question.minLength!) {
errors[questionId] = FormContentMessages.minCharacters(
locale,
question.minLength!,
);
continue;
}
if (question.maxLength != null && length > question.maxLength!) {
errors[questionId] = FormContentMessages.maxCharacters(
locale,
question.maxLength!,
);
continue;
}
}
final selected = answer is List<int>
? answer
: answer is int
? [answer]
: const <int>[];
if (selected.isNotEmpty || question.minSelected != null) {
if (question.minSelected != null &&
selected.length < question.minSelected!) {
errors[questionId] = FormContentMessages.minChoices(
locale,
question.minSelected!,
);
continue;
}
if (question.maxSelected != null &&
selected.length > question.maxSelected!) {
errors[questionId] = FormContentMessages.maxChoices(
locale,
question.maxSelected!,
);
}
}
}
return errors;
}