UNPKG

@astro-utils/forms

Version:

Server component for Astro (call server functions from client side with validation and state management)

44 lines (43 loc) 1.32 kB
import { z } from 'zod'; function validateEmptyFile(about) { const value = about.formValue; return value instanceof File && value.size == 0; } export function validateRequire(about, required) { if (about.formValue == null || about.formValue === '' || about.formValue instanceof Array && about.formValue.length === 0 || validateEmptyFile(about)) { if (required) { about.pushErrorManually('missing-require-filed', 'Missing required filed'); } return false; } return true; } export function validateStringPatters(about, minlength, maxlength, pattern) { let text = z.string(); if (minlength) { text = text.min(minlength); } if (maxlength) { text = text.max(maxlength); } if (pattern) { text = text.regex(pattern); } return about.catchParse(text); } export async function validateFunc(about, method) { try { const response = await method(about.formValue); if (!response) return; if (response.error) { about.pushErrorManually(response.code, response.error); } else if (response.value) { about.formValue = response.value; } } catch (err) { about.pushErrorManually(err.code ?? err.name, err.message); } }