53 lines
1.4 KiB
TypeScript
53 lines
1.4 KiB
TypeScript
import isCidr from "is-cidr";
|
|
import type { LenConstraint } from "../api/ServerApi";
|
|
|
|
/**
|
|
* Check if a constraint was respected or not
|
|
*
|
|
* @returns An error message appropriate for the constraint
|
|
* violation, if any, or undefined otherwise
|
|
*/
|
|
export function checkConstraint(
|
|
constraint: LenConstraint,
|
|
value: string | undefined
|
|
): string | undefined {
|
|
value = value ?? "";
|
|
if (value.length < constraint.min)
|
|
return `Please specify at least ${constraint.min} characters!`;
|
|
|
|
if (value.length > constraint.max)
|
|
return `Please specify at least ${constraint.min} characters!`;
|
|
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Check if a number constraint was respected or not
|
|
*
|
|
* @returns An error message appropriate for the constraint
|
|
* violation, if any, or undefined otherwise
|
|
*/
|
|
export function checkNumberConstraint(
|
|
constraint: LenConstraint,
|
|
value: number
|
|
): string | undefined {
|
|
value = value ?? "";
|
|
if (value < constraint.min)
|
|
return `Value is below accepted minimum (${constraint.min})!`;
|
|
|
|
if (value > constraint.max)
|
|
return `Value is above accepted maximum (${constraint.min})!`;
|
|
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Check whether a given IP network address is valid or not
|
|
*
|
|
* @param ip The IP network to check
|
|
* @returns true if the address is valid, false otherwise
|
|
*/
|
|
export function isIPNetworkValid(ip: string): boolean {
|
|
return isCidr(ip) !== 0;
|
|
}
|