@astro-utils/forms
Version:
Server component for Astro (call server functions from client side with validation and state management)
48 lines (47 loc) • 1.86 kB
JavaScript
import { getFormMultiValue } from '../form-tools/post.js';
import AboutFormName from './form-utils/about-form-name.js';
import { parseMultiDate, parseMultiNumber } from './form-utils/parse-multi.js';
import { validateRequire } from './form-utils/validate.js';
import { getProperty } from 'dot-prop';
export function stringifySelectValue(value) {
if (value instanceof Date) {
value = value.getTime();
}
return String(value);
}
async function getSelectValue(astro, bindId) {
const { value: originalValue, readonly, name } = astro.props;
if (readonly) {
return [originalValue].flat().map(stringifySelectValue);
}
return (await getFormMultiValue(astro.request, bindId + name)).map(String);
}
export async function validateSelect(astro, bind, bindId) {
const { type, required, name, multiple, errorMessage } = astro.props;
const parseValue = await getSelectValue(astro, bindId);
const aboutSelect = new AboutFormName(bind, name, parseValue, errorMessage);
if (!validateRequire(aboutSelect, required)) {
aboutSelect.setValue();
return [];
}
const selectPlugin = bind.getPlugin('HTMLSelectPlugin');
selectPlugin.addNewValue(aboutSelect, parseValue, multiple, required);
switch (type) {
case 'date':
parseMultiDate(aboutSelect);
break;
case 'number':
parseMultiNumber(aboutSelect);
break;
}
aboutSelect.setValue();
return parseValue;
}
export function validateSelectOption(bind, name, stringifyValue) {
const selectPlugin = bind.getPlugin('HTMLSelectPlugin');
selectPlugin.addOption(name, stringifyValue);
}
export function getSelectValueFromBind(bind, astro) {
const newValue = [getProperty(bind, astro.props.name, astro.props.value)].flat();
return newValue.map(stringifySelectValue);
}