Skip to content

A platform for community discussion. Free, open, simple.

FIX: only validate length when value is set (#31053)

Joffrey JAFFEUX92779a57d419
diff --git a/app/assets/javascripts/discourse/app/form-kit/lib/validator.js b/app/assets/javascripts/discourse/app/form-kit/lib/validator.js
index 22325995318..0eb1c0d51d1 100644
--- a/app/assets/javascripts/discourse/app/form-kit/lib/validator.js
+++ b/app/assets/javascripts/discourse/app/form-kit/lib/validator.js
@@ -35,6 +35,10 @@ export default class Validator {
}
lengthValidator(value, rule) {
+ if (isBlank(value)) {
+ return;
+ }
+
if (rule.max) {
if (value?.length > rule.max) {
return i18n("form_kit.errors.too_long", {
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/form-kit/validator-test.js b/app/assets/javascripts/discourse/tests/unit/lib/form-kit/validator-test.js
index 90e8254b036..3f233b5b062 100644
--- a/app/assets/javascripts/discourse/tests/unit/lib/form-kit/validator-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/lib/form-kit/validator-test.js
@@ -17,15 +17,15 @@ module("Unit | Lib | FormKit | Validator", function (hooks) {
});
test("length", async function (assert) {
- let errors = await new Validator("", {
- length: { min: 1, max: 5 },
+ let errors = await new Validator("a", {
+ length: { min: 2, max: 5 },
}).validate();
assert.deepEqual(
errors,
[
i18n("form_kit.errors.too_short", {
- count: 1,
+ count: 2,
}),
],
"it returns an error when the value is too short"
@@ -52,6 +52,15 @@ module("Unit | Lib | FormKit | Validator", function (hooks) {
[],
"it returns no errors when the value is valid"
);
+
+ errors = await new Validator("", {
+ length: { min: 1, max: 5 },
+ }).validate();
+ assert.deepEqual(
+ errors,
+ [],
+ "it returns no errors when the value is blank"
+ );
});
test("between", async function (assert) {