tianji/src/client/utils/validator.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

import { RuleObject } from 'antd/es/form';
import { z } from 'zod';
2024-01-24 13:26:42 +00:00
import { hostnameRegex, slugRegex } from '@tianji/shared';
type Validator = (
rule: RuleObject,
value: any,
callback: (error?: string) => void
) => Promise<void | any> | void;
export const hostnameValidator: Validator = (rule, value, callback) => {
try {
z.union([z.string().ip(), z.string().regex(hostnameRegex)]).parse(value);
callback();
} catch (err) {
callback('Not valid host, it should be ip or hostname');
}
};
export const domainValidator: Validator = (rule, value, callback) => {
try {
z.string().regex(hostnameRegex).parse(value);
callback();
} catch (err) {
callback('Not valid, it should be domain, for example: example.com');
}
};
export const urlSlugValidator: Validator = (rule, value, callback) => {
try {
z.string().regex(slugRegex).parse(value);
callback();
} catch (err) {
callback('Not valid slug');
}
};
2024-01-10 17:01:48 +00:00
export const portValidator: Validator = (rule, value, callback) => {
try {
z.number().min(1).max(65535).parse(value);
callback();
} catch (err) {
callback('Not valid port, it should be 1 ~ 65535');
}
};