UNPKG

@astro-utils/forms

Version:

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

46 lines (45 loc) 1.61 kB
import { setProperty } from 'dot-prop'; import { IHTMLFormPlugin } from './iform-plugin.js'; export default class HTMLSelectPlugin extends IHTMLFormPlugin { constructor() { super(...arguments); this.storage = new Map(); } static errorOptionNotValid(about) { about.pushErrorManually('option-not-valid', 'Select option not valid'); } createOneValidation(name, keyData) { const { options, multiOptions, value, about, required } = keyData; if (multiOptions) { const arrayValue = Array.isArray(value) ? value : [value]; if (!arrayValue.every(x => options.has(x))) { required && HTMLSelectPlugin.errorOptionNotValid(about); return; } setProperty(this.form, name, about.formValue); return; } if (!options.has(value[0])) { required && HTMLSelectPlugin.errorOptionNotValid(about); return; } setProperty(this.form, name, about.formValue[0]); } createSelectDefault(about, value, multiOptions, required) { return { about, options: new Set(), value, multiOptions, required }; } addNewValue(about, value, multiOptions, required = true) { if (!this.storage.has(about.originalName)) { this.storage.set(about.originalName, this.createSelectDefault(about, value, multiOptions, required)); } } addOption(originalName, option) { this.storage.get(originalName)?.options.add(option); } }