-
-
Notifications
You must be signed in to change notification settings - Fork 541
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
minLength validation only when not empty #259
Comments
My workaround is to do this: validators: [
(val) => val.isNotEmpty
? FormBuilderValidators.minLength(4).call(val)
: null,
], This is not awful, but I'm open to a more elegant solution. |
This actually sounds like an elegant suggestion, I'll consider having it added. |
When the field is truly required, adding However, when the field is not required, adding the flexibility to validators: [
FormBuilderValidators.minLength(4, allowEmpty: true),
], |
I just tried using this and it did not work: FormBuilderValidators.minLength(4, allowEmpty: true), Alas, I get a "Value must have a length greater than or equal to 4." message when the field is blank. The implementation is presently: static FormFieldValidator minLength(
num minLength, {
bool allowEmpty = false,
String errorText,
}) {
return (valueCandidate) {
if (allowEmpty && (valueCandidate == null || valueCandidate?.length == 0))
return errorText ??
"Value must have a length greater than or equal to $minLength";
if (valueCandidate != null && valueCandidate.length < minLength) {
return errorText ??
"Value must have a length greater than or equal to $minLength";
}
return null;
};
} May I recommend this alternative: static FormFieldValidator minLength(
num minLength, {
bool allowEmpty = false,
String errorText,
}) {
return (valueCandidate) {
final valueLength = valueCandidate?.length ?? 0;
if (valueLength < minLength && (!allowEmpty || valueLength > 0)) {
return errorText ??
"Value must have a length greater than or equal to $minLength";
}
return null;
};
} |
HI @awhitford, Could you be kind enough to submit a PR for this? |
Note that I see that you added |
PR has been submitted. However, please note that I was unable to completely validate it because the build is broken:
I assume that this is work in progress. |
Confirmed that this now works great with version 3.10.0. Thank you! |
I only want the
minLength
validation when a value is specified; an empty field is fine.It seems that this is arguably redundant:
I thought I could simply remove the
required()
validator, butminLength(4)
still complains that the empty field is not at least 4 characters.Maybe the
minLength
validator could have an optional flag to say whether it should apply to empty fields? (That way, backwards compatibility can be maintained.)The text was updated successfully, but these errors were encountered: