-
Notifications
You must be signed in to change notification settings - Fork 192
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add custom validation #291
Comments
You can find examples in the docs: https://giancarlocode.github.io/form_bloc/#/. For example inside the "Validation Based on other Field" tab: final password = TextFieldBloc(
validators: [FieldBlocValidators.required],
);
final confirmPassword = TextFieldBloc(
validators: [FieldBlocValidators.required],
);
Validator<String> _confirmPassword(
TextFieldBloc passwordTextFieldBloc,
) {
return (String? confirmPassword) {
if (confirmPassword == passwordTextFieldBloc.value) {
return null;
}
return 'Must be equal to password';
};
}
ValidationBasedOnOtherFieldFormBloc() {
addFieldBlocs(
fieldBlocs: [password, confirmPassword],
);
confirmPassword
..addValidators([_confirmPassword(password)])
..subscribeToFieldBlocs([password]);
// Or you can use built-in confirm password validator
// confirmPassword
// ..addValidators([FieldBlocValidators.confirmPassword(password)])
// ..subscribeToFieldBlocs([password]);
}
}``` |
Can you add custom validators for an InputFieldBloc? I've been trying to figure it out for a date for like 2 weeks now |
Hi, @frostythedev You can for sure. What are you difficulties? Can you show some code? |
Sure, I didn't get a notification but I'm trying to validate DateTime field blocs so that they cannot be selected to a day in the past and not before other DateTime field blocs. I tried AsyncFieldValidaiton, validation based on the same field, validation based on other fields, DateTime does not seem to respond to any as it will not validate at all. Included are the methods I tried: ` Future<DateTime?> _checkDate(DateTime? toCheck) async {
}
}
} ` |
@frostythedev It is hard to read and give advice without runnable code. But for the attempts that given by you, second one seems a good try. It seems you are not using the dateNow to validate. |
@frostythedev It should be something like this Validator<DateTime?> _dateBeforeCurrent(InputFieldBloc<DateTime?, dynamic> dateBloc) {
return (DateTime? dateTime){
DateTime now = DateTime.now();
print('validating date');
if(dateBloc.value!.isAfter(now) || (dateTime?.isAfter(now) ?? false) || (dateTime?.isAfter(dateBloc.value!) ?? false)){
print('date is good (after current)');
return null;
}
print('date is not good (before current)');
return now;
};
} If you need more help, more information is needed to identify what you did wrong. A runnable example is required to let us review the code on the same page. |
How I can add custom validation, to add validation errors in another language??
The text was updated successfully, but these errors were encountered: