npm install -D @voscausa/svelte-use-validate
// rulesConfig = { node.id: rule or [rulechain ...], ...}
const rulesConfig = {
day: ["required", { range: { min: 1, max: 31 } }, "dayOk"],
month: ["required", { range: { min: 1, max: 12 } }],
grossValue: ["required", "cents"],
section: ["required", "sectionContra"], // optional contra
contra: "get", // get default: "" if section has no contra
note: "get",
account_number: ["required", "ibanNum"], // alt rule with ibanRuleChains(iban)
iban: "ibanType", // alt rule with ibanRuleChains(iban)
title: ["required", { len: { operator: ">=", len: 10, msg: "length must be >= 10" } }],
};
import { validate } from "@voscausa/svelte-use-validate";
// not valid markers for components
const notValidMarkers = { contra: false, section: false, grossValue: false };
const { field, OK, addValidator, fieldValues, runRuleChain } = validate(
{ rulesConfig, lazy: true, markDefault: 3 , alertBelow: 0, setNotValid},
(id, notValid, value) => {
// callback to update bindings or signal notValid components
if (id in notValidMarkers) notValidMarkers[id] = notValid;
}
);
Validate instance config options:
true
)0
)Validator functions have two types of arguments:
node.name
(a unique id for an html element)3
)A validator returns notValid (true or false). True breaks the rule chain.
use:field={value} or use:field={obj}
// where the value / obj argument will be decomposed as show below:
let { value, id = node.name, mark = 3, controls = [] } = obj;
// alt rulechain selection to validate an account_number
addValidator("ibanType", function () {
runRuleChain.account_number(
// here we use the iban bool as a control
this.value
? ["required", "ibanNum"]
: ["required", { len: { operator: ">=", len: 3, msg: "not IBAN; length must be > 3" } }]
);
// this iban validator is always OK, return false (bool always OK)
return false;
});
// alt rulechain selection to validate an optional contra
addValidator("sectionContra", function () {
runRuleChain.contra(
// hasContra control => require a contra account input
this.controls[0]
? ["required", { func: { fn: validContraSection, msg: "contra section missing" } }]
: "get" // no contra account => contra account = ""
);
// this section validator is always OK, so return false
return false;
});
An example Svelte SPA can be found here: voscausa/use-validate-example