DEV: adds an integer validation rule to form-kit (#27985)

Usage:

```
@validation="integer"
```

This commit also adds a default for rules. By default a rule will now be `ruleName: {}`, this avoids all the boilerplate in validation-parser.js.
This commit is contained in:
Joffrey JAFFEUX 2024-07-19 12:39:26 +02:00 committed by GitHub
parent 5038cad68e
commit b10b485572
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 27 additions and 17 deletions

View File

@ -11,7 +11,7 @@ export default class ValidationParser {
if (this[ruleName + "Rule"]) {
rules[ruleName] = this[ruleName + "Rule"](args);
} else {
throw new Error(`Unknown rule: ${ruleName}`);
rules[ruleName] = {};
}
});
@ -25,18 +25,6 @@ export default class ValidationParser {
};
}
urlRule() {
return {};
}
acceptedRule() {
return {};
}
numberRule() {
return {};
}
betweenRule(args) {
if (!args) {
throw new Error("`between` rule expects min/max, eg: between:1,10");

View File

@ -27,6 +27,12 @@ export default class Validator {
return errors;
}
integerValidator(value) {
if (!Number.isInteger(Number(value))) {
return I18n.t("form_kit.errors.not_an_integer");
}
}
lengthValidator(value, rule) {
if (rule.max) {
if (value?.length > rule.max) {

View File

@ -12,10 +12,6 @@ module("Unit | Lib | FormKit | ValidationParser", function (hooks) {
assert.deepEqual(rules.url, {});
});
test("unknown rule", function (assert) {
assert.throws(() => ValidationParser.parse("foo"), "Unknown rule: foo");
});
test("required", function (assert) {
const rules = ValidationParser.parse("required");

View File

@ -92,6 +92,25 @@ module("Unit | Lib | FormKit | Validator", function (hooks) {
);
});
test("integer", async function (assert) {
let errors = await new Validator(1.2, {
integer: {},
}).validate();
assert.deepEqual(
errors,
[I18n.t("form_kit.errors.not_an_integer")],
"it returns an error when the value is not an integer"
);
errors = await new Validator(1, { integer: {} }).validate();
assert.deepEqual(
errors,
[],
"it returns no errors when the value is an integer"
);
});
test("number", async function (assert) {
let errors = await new Validator("A", {
number: {},

View File

@ -2105,6 +2105,7 @@ en:
errors:
required: "Required"
invalid_url: "Must be a valid URL"
not_an_integer: "Must be an integer"
not_accepted: "Must be accepted"
not_a_number: "Must be a number"
too_high: "Must be at most %{count}"