onsubmit
Version:
Simple validation utilities in typescript.
54 lines (52 loc) • 1.67 kB
TypeScript
interface CustomFunction {
(value: string): boolean;
}
interface KeyValuePair {
[key: string]: string;
}
type Criterion = string | number | CustomFunction | boolean | RegExp;
interface Rule<TCriterion = Criterion> {
criterion: TCriterion;
message: string;
}
interface RequiredRule extends Rule<boolean> {
}
interface MinLengthRule extends Rule<number> {
}
interface MaxLengthRule extends Rule<number> {
}
interface PatternRule extends Rule<RegExp> {
}
interface CustomRule extends Rule<CustomFunction> {
}
interface RulesObject {
required?: RequiredRule;
minLength?: MinLengthRule;
maxLength?: MaxLengthRule;
pattern?: PatternRule;
custom?: CustomRule;
}
type FormDataShape = KeyValuePair | {
[k: string]: FormDataEntryValue;
};
interface FieldError {
name: string;
message: string;
}
interface NameRuleMap {
[key: string]: RulesObject;
}
type ValidationFunction<TCriterion> = (value: string, criterion: TCriterion, message: string) => void;
type MinLengthFunction = ValidationFunction<number>;
type MaxLengthFunction = ValidationFunction<number>;
type PatternFunction = ValidationFunction<RegExp>;
type CustomFunctionType = ValidationFunction<CustomFunction>;
type RequiredFunction = ValidationFunction<boolean>;
type ConfigMap = {
minLength?: MinLengthFunction;
maxLength?: MaxLengthFunction;
pattern?: PatternFunction;
custom?: CustomFunctionType;
required?: RequiredFunction;
};
export { ConfigMap, Criterion, CustomFunction, CustomRule, FieldError, FormDataShape, KeyValuePair, MaxLengthRule, MinLengthRule, NameRuleMap, PatternRule, RequiredRule, Rule, RulesObject, ValidationFunction };