mirror of
https://github.com/discourse/discourse.git
synced 2024-11-22 19:46:55 +08:00
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:
parent
5038cad68e
commit
b10b485572
|
@ -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");
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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");
|
||||
|
||||
|
|
|
@ -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: {},
|
||||
|
|
|
@ -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}"
|
||||
|
|
Loading…
Reference in New Issue
Block a user