@overgaming/valiform 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -13
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +80 -76
- package/dist/src/context/useFieldContext.d.ts +37 -1
- package/dist/src/types.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,8 +14,7 @@ npm install @overgaming/valiform
|
|
|
14
14
|
|
|
15
15
|
```ts
|
|
16
16
|
import { createApp } from 'vue';
|
|
17
|
-
import { FormsPlugin } from '@overgaming/valiform';
|
|
18
|
-
import { es } from '@overgaming/valiform/locales';
|
|
17
|
+
import { FormsPlugin, es } from '@overgaming/valiform';
|
|
19
18
|
|
|
20
19
|
const app = createApp(App);
|
|
21
20
|
|
|
@@ -63,11 +62,9 @@ Build a custom input component using `useFieldContext` and `defineModel`:
|
|
|
63
62
|
<script setup lang="ts">
|
|
64
63
|
import { useFieldContext } from '@overgaming/valiform';
|
|
65
64
|
|
|
66
|
-
defineProps({
|
|
67
|
-
type: { type: String, default: 'text' }
|
|
68
|
-
});
|
|
65
|
+
withDefaults(defineProps<{ type?: string }>(), { type: 'text' });
|
|
69
66
|
|
|
70
|
-
const model = defineModel({
|
|
67
|
+
const model = defineModel<string>({ default: '' });
|
|
71
68
|
const { inputValue, inputProps, error } = useFieldContext({ inputValue: model });
|
|
72
69
|
</script>
|
|
73
70
|
```
|
|
@@ -245,17 +242,34 @@ Access the parent `<Form>` state from any descendant component.
|
|
|
245
242
|
const { values, isValid, errors, reset, validate, setErrors } = useFormContext();
|
|
246
243
|
```
|
|
247
244
|
|
|
248
|
-
### `useFieldContext(
|
|
245
|
+
### `useFieldContext()`
|
|
249
246
|
|
|
250
|
-
Access the parent `<Field>` state from any descendant component.
|
|
247
|
+
Access the parent `<Field>` state from any descendant component.
|
|
251
248
|
|
|
252
|
-
|
|
253
|
-
// Basic usage
|
|
254
|
-
const { inputValue, inputProps, error, isValid, isTouched, isDirty } = useFieldContext();
|
|
249
|
+
Has three call signatures:
|
|
255
250
|
|
|
256
|
-
|
|
257
|
-
|
|
251
|
+
```ts
|
|
252
|
+
// No args — component must always be inside a Field.
|
|
253
|
+
// Returns FieldContext directly (no ! needed).
|
|
254
|
+
// Throws at runtime if called outside a Field.
|
|
255
|
+
const { labelProps } = useFieldContext();
|
|
256
|
+
|
|
257
|
+
// With fallback — component works inside or outside a Field.
|
|
258
|
+
// Returns FieldContext directly (no ! needed).
|
|
259
|
+
// When outside a Field, the fallback object is used instead.
|
|
260
|
+
const model = defineModel<string>({ default: '' });
|
|
258
261
|
const { inputValue, inputProps, error } = useFieldContext({ inputValue: model });
|
|
262
|
+
|
|
263
|
+
// Explicit null — handle absence of context manually.
|
|
264
|
+
// Returns FieldContext | null.
|
|
265
|
+
const ctx = useFieldContext(null);
|
|
266
|
+
if (ctx) { ... }
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
TypeScript types for `FieldContext` and other interfaces are exported from the package:
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import type { FieldContext, FieldState, FormContext } from '@overgaming/valiform';
|
|
259
273
|
```
|
|
260
274
|
|
|
261
275
|
### `useLocale()`
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("vue"),C=Symbol("locale-context"),T=(e=null)=>{const t=o.inject(C,e);if(!t&&t!==null)throw new Error("Context with localeContextKey not found");return t},q={required:"This field is required",email:"Please enter a valid email address",min:({value:e})=>`Must be at least ${e}`,max:({value:e})=>`Must be at most ${e}`,matches:"Format is not valid",number:"Must be a valid number",accepted:"Must be accepted",alpha:"Must contain only alphabetical characters",alphanumeric:"Must contain only letters and numbers",alphaSpaces:"Must contain only letters and spaces",between:({min:e,max:t})=>`Must be between ${e} and ${t}`,confirm:({fieldName:e})=>`Must match ${e}`,containsAlpha:"Must contain at least one letter",containsAlphanumeric:"Must contain at least one letter or number",containsAlphaSpaces:"Must contain at least one letter or space",containsLowercase:"Must contain at least one lowercase letter",containsNumeric:"Must contain at least one number",containsSymbol:"Must contain at least one symbol",containsUppercase:"Must contain at least one uppercase letter",dateAfter:({date:e})=>e?`Must be after ${e}`:"Must be after today",dateAfterOrEqual:({date:e})=>e?`Must be after or equal to ${e}`:"Must be after or equal to today",dateBefore:({date:e})=>e?`Must be before ${e}`:"Must be before today",dateBeforeOrEqual:({date:e})=>e?`Must be before or equal to ${e}`:"Must be before or equal to today",dateBetween:({startDate:e,endDate:t})=>`Must be between ${e} and ${t}`,dateFormat:({format:e})=>`Must match the format ${e}`,endsWith:({suffix:e})=>Array.isArray(e)?`Must end with one of: ${e.map(t=>`"${t}"`).join(", ")}`:`Must end with "${e}"`,is:({allowedValues:e})=>`Must be one of: ${Array.isArray(e)?e.join(", "):e}`,length:({value:e,min:t,max:n})=>t!==void 0&&n!==void 0?`Must be between ${t} and ${n} characters`:e!==void 0?`Must be exactly ${e} characters`:"Invalid length",lowercase:"Must contain only lowercase characters",not:({disallowedValues:e})=>`Must not be one of: ${Array.isArray(e)?e.join(", "):e}`,startsWith:({prefix:e})=>Array.isArray(e)?`Must start with one of: ${e.join(", ")}`:`Must start with "${e}"`,symbol:"Must contain only symbols",uppercase:"Must contain only uppercase characters",url:"Must be a valid URL"},E=o.shallowRef(new Map),_=(e,t)=>{E.value.set(e,t)},V=e=>{Object.entries(e).forEach(([t,n])=>{_(t,n)})},z=e=>E.value.get(e);function I(e){const t=e.accepted;return typeof t=="function"?t({}):t??"Must be accepted"}function K(e){return e?["yes","on","1","true"].includes(String(e).toLowerCase()):!1}function U(e,t={}){const{messages:n={}}=t;return K(e)?!0:I(n)}function k(e){const t=e.alpha;return typeof t=="function"?t({}):t??"Must contain only alphabetical characters"}function Z(e){return e?/^[a-zA-Z]+$/.test(String(e)):!0}function Y(e,t={}){const{messages:n={}}=t;return Z(e)?!0:k(n)}function G(e){const t=e.alphanumeric;return typeof t=="function"?t({}):t??"Must contain only letters and numbers"}function H(e){return e?/^[a-zA-Z0-9]+$/.test(String(e)):!0}function J(e,t={}){const{messages:n={}}=t;return H(e)?!0:G(n)}function Q(e){const t=e.alphaSpaces;return typeof t=="function"?t({}):t??"Must contain only letters and spaces"}function X(e){return e?/^[a-zA-Z\s]+$/.test(String(e)):!0}function ee(e,t={}){const{messages:n={}}=t;return X(e)?!0:Q(n)}function te(e,t,n){const r=e.between;return typeof r=="function"?r({min:t,max:n}):r??`Must be between ${t} and ${n}`}function ne(e,t,n){if(!e&&e!==0)return!0;const r=Number(e);if(isNaN(r))return!1;const s=Number(t),a=Number(n);return isNaN(s)||isNaN(a)?!1:r>=s&&r<=a}function re(e,t={}){const{args:n=[],messages:r={}}=t,[s,a]=n;return ne(e,s,a)?!0:te(r,s,a)}function se(e,t){const n=e.confirm;return typeof n=="function"?n({fieldName:t}):n??`Must match ${t}`}function oe(e,t,n){var r;return e?n?e===((r=n[t])==null?void 0:r.value):!1:!0}function ae(e,t={}){const{args:n=[],messages:r={},fields:s={}}=t,[a]=n;return oe(e,a,s)?!0:se(r,a)}function ue(e){const t=e.containsAlpha;return typeof t=="function"?t({}):t??"Must contain at least one letter"}function ie(e){return e?/[a-zA-Z]/.test(String(e)):!0}function ce(e,t={}){const{messages:n={}}=t;return ie(e)?!0:ue(n)}function le(e){const t=e.containsAlphanumeric;return typeof t=="function"?t({}):t??"Must contain at least one letter or number"}function fe(e){return e?/[a-zA-Z0-9]/.test(String(e)):!0}function me(e,t={}){const{messages:n={}}=t;return fe(e)?!0:le(n)}function de(e){const t=e.containsAlphaSpaces;return typeof t=="function"?t({}):t??"Must contain at least one letter or space"}function ge(e){return e?/[a-zA-Z\s]/.test(String(e)):!0}function pe(e,t={}){const{messages:n={}}=t;return ge(e)?!0:de(n)}function be(e){const t=e.containsLowercase;return typeof t=="function"?t({}):t??"Must contain at least one lowercase letter"}function ye(e){return e?/[a-z]/.test(String(e)):!0}function $e(e,t={}){const{messages:n={}}=t;return ye(e)?!0:be(n)}function he(e){const t=e.containsNumeric;return typeof t=="function"?t({}):t??"Must contain at least one number"}function ve(e){return e?/\d/.test(String(e)):!0}function Me(e,t={}){const{messages:n={}}=t;return ve(e)?!0:he(n)}function we(e){const t=e.containsSymbol;return typeof t=="function"?t({}):t??"Must contain at least one symbol"}function Ne(e){return e?/[^\w\s]/.test(String(e)):!0}function Ae(e,t={}){const{messages:n={}}=t;return Ne(e)?!0:we(n)}function De(e){const t=e.containsUppercase;return typeof t=="function"?t({}):t??"Must contain at least one uppercase letter"}function Se(e){return e?/[A-Z]/.test(String(e)):!0}function Fe(e,t={}){const{messages:n={}}=t;return Se(e)?!0:De(n)}function xe(e,t){const n=e.dateAfter;return typeof n=="function"?n({date:t}):n??(t?`Must be after ${t}`:"Must be after today")}function Ve(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n>r}function je(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Ve(e,s)?!0:xe(r,s)}function Pe(e,t){const n=e.dateAfterOrEqual;return typeof n=="function"?n({date:t}):n??(t?`Must be after or equal to ${t}`:"Must be after or equal to today")}function Ce(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n>=r}function Te(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Ce(e,s)?!0:Pe(r,s)}function qe(e,t){const n=e.dateBefore;return typeof n=="function"?n({date:t}):n??(t?`Must be before ${t}`:"Must be before today")}function Ee(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n<r}function Be(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Ee(e,s)?!0:qe(r,s)}function Oe(e,t){const n=e.dateBeforeOrEqual;return typeof n=="function"?n({date:t}):n??(t?`Must be before or equal to ${t}`:"Must be before or equal to today")}function Re(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n<=r}function Le(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Re(e,s)?!0:Oe(r,s)}function We(e,t,n){const r=e.dateBetween;return typeof r=="function"?r({startDate:t,endDate:n}):r??`Must be between ${t} and ${n}`}function _e(e,t,n){if(!e)return!0;const r=new Date(String(e)),s=new Date(t),a=new Date(n);return!isNaN(r.getTime())&&!isNaN(s.getTime())&&!isNaN(a.getTime())&&r>=s&&r<=a}function ze(e,t={}){const{args:n=[],messages:r={}}=t,[s,a]=n;return _e(e,s,a)?!0:We(r,s,a)}const Ie=e=>{const t=e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),n={YYYY:"\\d{4}",YY:"\\d{2}",MM:"(0[1-9]|1[012])",M:"([1-9]|1[012])",DD:"([012][0-9]|3[01])",D:"([012]?[0-9]|3[01])"};let r=t;return Object.keys(n).forEach(s=>{r=r.replace(new RegExp(s,"g"),n[s])}),new RegExp(`^${r}$`)};function Ke(e,t){const n=e.dateFormat;return typeof n=="function"?n({format:t}):n??`Must match the format ${t}`}function Ue(e,t){return e?t&&typeof t=="string"?Ie(t).test(String(e)):!isNaN(Date.parse(String(e))):!0}function ke(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Ue(e,s)?!0:Ke(r,s)}function Ze(e){const t=e.email;return typeof t=="function"?t({}):t??"Please enter a valid email address"}function Ye(e){return e?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(e)):!0}function Ge(e,t={}){const{messages:n={}}=t;return Ye(e)?!0:Ze(n)}function He(e,t){const n=e.endsWith;return typeof n=="function"?n({suffix:t.length===1?t[0]:t}):n??`Must end with: ${t.join(", ")}`}function Je(e,...t){if(!e)return!0;const n=String(e);return t.some(r=>n.endsWith(r))}function Qe(e,t={}){const{args:n=[],messages:r={}}=t;return Je(e,...n)?!0:He(r,n)}function Xe(e,t){const n=e.is;return typeof n=="function"?n({allowedValues:t}):n??`Must be one of: ${t.join(", ")}`}function et(e,...t){return!e&&e!==0&&e!==!1?!0:t.includes(String(e))}function tt(e,t={}){const{args:n=[],messages:r={}}=t;return et(e,...n)?!0:Xe(r,n)}function nt(e,t,n){const r=e.length;return n!==void 0?typeof r=="function"?r({min:t,max:n}):r??`Must be between ${t} and ${n} characters`:typeof r=="function"?r({value:t}):r??`Must be exactly ${t} characters`}function rt(e,t,n){if(!e&&e!==0)return!0;let r=0;if(typeof e=="string")r=e.length;else if(Array.isArray(e))r=e.length;else if(typeof e=="object"&&e!==null)r=Object.keys(e).length;else return!1;if(n!==void 0){const a=Number(t),u=Number(n);return!isNaN(a)&&!isNaN(u)&&r>=a&&r<=u}const s=Number(t);return!isNaN(s)&&r===s}function st(e,t={}){const{args:n=[],messages:r={}}=t,[s,a]=n;return rt(e,s,a)?!0:nt(r,s,a)}function ot(e){const t=e.lowercase;return typeof t=="function"?t({}):t??"Must contain only lowercase characters"}function at(e){return e?/^[a-z]+$/.test(String(e)):!0}function ut(e,t={}){const{messages:n={}}=t;return at(e)?!0:ot(n)}function it(e,t,n){const r=t.matches;return typeof r=="function"?r({value:e,pattern:n}):r??"Format is not valid"}function ct(e,t){if(!e)return!0;if(!t)return!1;try{if(t.startsWith("/")&&t.includes("/",1)){const n=t.lastIndexOf("/"),r=t.slice(1,n),s=t.slice(n+1);return new RegExp(r,s).test(String(e))}return String(e)===t}catch{return!1}}function lt(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return ct(e,s)?!0:it(e,r,s)}function ft(e,t){const n=e.max;return typeof n=="function"?n({value:t}):n??`Must be at most ${t}`}function mt(e,t){if(!e&&e!==0)return!0;const n=Number(t);if(isNaN(n))return!1;if(typeof e=="number")return e<=n;if(typeof e=="string"){const r=Number(e);return isNaN(r)?e.length<=n:r<=n}return Array.isArray(e)?e.length<=n:!1}function dt(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return mt(e,s)?!0:ft(r,s)}function gt(e,t){const n=e.min;return typeof n=="function"?n({value:t}):n??`Must be at least ${t}`}function pt(e,t){if(!e&&e!==0)return!0;const n=Number(t);if(isNaN(n))return!1;if(typeof e=="number")return e>=n;if(typeof e=="string"){const r=Number(e);return isNaN(r)?e.length>=n:r>=n}return Array.isArray(e)?e.length>=n:!1}function bt(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return pt(e,s)?!0:gt(r,s)}function yt(e,t){const n=e.not;return typeof n=="function"?n({disallowedValues:t}):n??`Must not be one of: ${t.join(", ")}`}function $t(e,...t){return!e&&e!==0&&e!==!1?!0:!t.includes(String(e))}function ht(e,t={}){const{args:n=[],messages:r={}}=t;return $t(e,...n)?!0:yt(r,n)}function vt(e){const t=e.number;return typeof t=="function"?t({}):t??"Must be a valid number"}function Mt(e){if(e==null||e==="")return!0;if(Number.isNaN(e))return!1;const t=Number(e);return!isNaN(t)&&isFinite(t)}function wt(e,t={}){const{messages:n={}}=t;return Mt(e)?!0:vt(n)}function Nt(e){const t=e.required;return typeof t=="function"?t({}):t??"This field is required"}function At(e){return e==null||e===""?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:e===0?!0:!!e}function Dt(e,t={}){const{messages:n={}}=t;return At(e)?!0:Nt(n)}function St(e,t){const n=e.startsWith;return typeof n=="function"?n({prefix:t.length===1?t[0]:t}):n??`Must start with: ${t.join(", ")}`}function Ft(e,...t){if(!e)return!0;const n=String(e);return t.some(r=>n.startsWith(r))}function xt(e,t={}){const{args:n=[],messages:r={}}=t;return Ft(e,...n)?!0:St(r,n)}function Vt(e){const t=e.symbol;return typeof t=="function"?t({}):t??"Must contain only symbols"}function jt(e){return e?/^[^\w\s]+$/.test(String(e)):!0}function Pt(e,t={}){const{messages:n={}}=t;return jt(e)?!0:Vt(n)}function Ct(e){const t=e.uppercase;return typeof t=="function"?t({}):t??"Must contain only uppercase characters"}function Tt(e){return e?/^[A-Z]+$/.test(String(e)):!0}function qt(e,t={}){const{messages:n={}}=t;return Tt(e)?!0:Ct(n)}function Et(e){const t=e.url;return typeof t=="function"?t({}):t??"Must be a valid URL"}function Bt(e){if(!e)return!0;try{const t=new URL(String(e));return["http:","https:","ftp:","ftps:"].includes(t.protocol)}catch{return!1}}function Ot(e,t={}){const{messages:n={}}=t;return Bt(e)?!0:Et(n)}const Rt=Object.freeze(Object.defineProperty({__proto__:null,accepted:U,alpha:Y,alphaSpaces:ee,alphanumeric:J,between:re,confirm:ae,containsAlpha:ce,containsAlphaSpaces:pe,containsAlphanumeric:me,containsLowercase:$e,containsNumeric:Me,containsSymbol:Ae,containsUppercase:Fe,dateAfter:je,dateAfterOrEqual:Te,dateBefore:Be,dateBeforeOrEqual:Le,dateBetween:ze,dateFormat:ke,email:Ge,endsWith:Qe,is:tt,length:st,lowercase:ut,matches:lt,max:dt,min:bt,not:ht,number:wt,required:Dt,startsWith:xt,symbol:Pt,uppercase:qt,url:Ot},Symbol.toStringTag,{value:"Module"})),Lt={install(e,t={}){V(Rt),t.rules&&V(t.rules);const n=o.isRef(t.locale)?t.locale:o.ref(t.locale??"en"),r={en:q};t.locales&&Object.keys(t.locales).forEach(a=>{r[a]={...r[a]??{},...t.locales[a]}});const s=o.shallowRef(r);e.provide(C,{locale:o.readonly(n),locales:o.readonly(s),setLocale:a=>{s.value[a]?n.value=a:console.warn(`Locale "${a}" not available.`)}})}},B=Symbol("form-state-context"),Wt=e=>{o.provide(B,e)},_t=(e=null)=>{const t=o.inject(B,e);if(!t&&t!==null)throw new Error("Context with formStateContextKey not found");return t},O=Symbol("form-context"),zt=e=>{o.provide(O,e)},It=(e=null)=>{const t=o.inject(O,e);if(!t&&t!==null)throw new Error("Context with formContextKey not found");return t};function Kt(e,t){if(!(!e||!t))return t.split(".").reduce((n,r)=>n==null?void 0:n[r],e)}function Ut(e,t,n){if(!e||!t)return e;const r=t.split("."),s=r.pop(),a=r.reduce((u,d,c)=>{if(u[d]===null||u[d]===void 0){const y=r[c+1]||s;u[d]=/^\d+$/.test(y)?[]:{}}return u[d]},e);return a[s]=n,e}const kt=o.defineComponent({__name:"Form",props:{modelValue:{default:()=>({})},modelModifiers:{}},emits:o.mergeModels(["submit"],["update:modelValue"]),setup(e,{emit:t}){const n=t,r=o.useModel(e,"modelValue");o.isReactive(r.value)||(r.value=o.reactive(r.value??{}));const s=o.ref({}),a=o.ref([]),u=o.computed(()=>r.value),d=o.computed(()=>a.value[0]??null),c=o.computed(()=>Object.keys(s.value).every(i=>s.value[i].isValid)),y=()=>{Object.keys(s.value).forEach(i=>{var p,g;(g=(p=s.value[i]).validate)==null||g.call(p)})},l=()=>{y(),c.value&&(a.value=[],n("submit",r.value,{setErrors:f,reset:m}))},f=(...i)=>{var p;if(i.length===1){const g=i[0];if(typeof g=="object"&&!Array.isArray(g)&&g!==null){Object.keys(g).forEach($=>{f($,g[$])});return}a.value=Array.isArray(g)?g:[g]}else if(i.length===2){const[g,$]=i;(p=s.value[g])==null||p.setErrors($)}},m=()=>{a.value=[],Object.keys(s.value).forEach(i=>{s.value[i].reset()})};return Wt({getFields(){return s.value},getField(i){return s.value[i]},addField(i,p){s.value[i]=p},removeField(i){delete s.value[i]},setFieldValue(i,p){Ut(r.value,i,p)},getFieldValue(i){return Kt(r.value,i)}}),zt({values:u,isValid:c,error:d,errors:a,fields:s,reset:m,setErrors:f,validate:y}),(i,p)=>(o.openBlock(),o.createElementBlock("form",{onSubmit:o.withModifiers(l,["prevent"])},[o.renderSlot(i.$slots,"default",o.normalizeProps(o.guardReactiveProps({isValid:c.value,error:d.value,errors:a.value,values:u.value,fields:s.value,reset:m,setErrors:f,validate:y})))],32))}});function R(e){if(!e||typeof e!="string")return{};const t=e.split("|").filter(Boolean),n={};for(const r of t){const[s,...a]=r.split(":"),u=s.trim();if(a.length===0)n[u]=!0;else{const c=a.join(":").split(",").map(y=>y.trim());n[u]=c.length===1?c[0]:c}}return n}const Zt=(e,t,n={},r={})=>{if(!t)return!0;const s=R(t),a=[];for(const[u,d]of Object.entries(s)){const c=z(u);if(c){const l={args:d===!0?[]:Array.isArray(d)?d:[d],messages:n,fields:r},f=c(e,l);f!==!0&&a.push(f??"Invalid value")}else console.warn(`[Forms] Validation rule "${u}" not found.`)}return a.length===0?!0:a},Yt=(e,t)=>{const n=t(e);return n===!0?!0:typeof n=="string"?[n]:Array.isArray(n)?n:!!n?!0:["Invalid value"]};typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const j=()=>{};function Gt(e,t){function n(...r){return new Promise((s,a)=>{Promise.resolve(e(()=>t.apply(this,r),{fn:t,thisArg:this,args:r})).then(s).catch(a)})}return n}const Ht=e=>e();function Jt(e,t={}){let n,r,s=j;const a=c=>{clearTimeout(c),s(),s=j};let u;return c=>{const y=o.toValue(e),l=o.toValue(t.maxWait);return n&&a(n),y<=0||l!==void 0&&l<=0?(r&&(a(r),r=void 0),Promise.resolve(c())):new Promise((f,m)=>{s=t.rejectOnCancel?m:f,u=c,l&&!r&&(r=setTimeout(()=>{n&&a(n),r=void 0,f(u())},l)),n=setTimeout(()=>{r&&a(r),r=void 0,f(c())},y)})}}function Qt(e,t,n={}){const{eventFilter:r=Ht,...s}=n;return o.watch(e,Gt(r,t),s)}function P(e,t,n={}){const{debounce:r=0,maxWait:s=void 0,...a}=n;return Qt(e,t,{...a,eventFilter:Jt(r,{maxWait:s})})}function Xt(e,t={}){const n=o.ref(!0),r=o.ref(!1),s=o.ref([]),a=o.ref(null),u=o.computed(()=>o.toValue(t.rules)??null),d=o.computed(()=>o.toValue(t.messages)??{}),c=o.computed(()=>o.toValue(t.fields)??{}),y=o.computed(()=>{if(!u.value||typeof u.value!="string")return null;const i=R(u.value).confirm;if(!i||i===!0)return null;const p=c.value[i];return(p==null?void 0:p.value)??null}),l=()=>{let m;return typeof u.value=="function"?m=Yt(o.toValue(e),u.value):m=Zt(o.toValue(e),u.value,d.value,c.value),m===!0?(n.value=!0,s.value=[],!0):Array.isArray(m)?(n.value=!1,s.value=m,!1):m},f=()=>{a.value&&clearTimeout(a.value),r.value=!0,n.value=!0,s.value=[],a.value=setTimeout(()=>{r.value=!1,a.value=null},1e3)};return P(()=>o.toValue(e),()=>{r.value||l()},{debounce:300}),P(()=>o.toValue(y),()=>{r.value||o.toValue(e)&&l()},{debounce:300}),{validate:l,reset:f,isValid:o.readonly(n),errors:o.readonly(s)}}const L=Symbol("field-context"),en=e=>{o.provide(L,e)},tn=(e=null)=>{const t=o.inject(L,e);if(!t&&t!==null)throw new Error("Context with fieldContextKey not found");return t},nn=o.defineComponent({__name:"Field",props:o.mergeModels({id:{},name:{},validation:{type:[String,Function,null]},validationMessages:{},error:{}},{modelValue:{},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const t=e,n=o.useModel(e,"modelValue"),r=o.useId(),s=_t(),a=T(),u=o.computed({get:()=>s?s.getFieldValue(t.name):n.value,set:b=>{s?s.setFieldValue(t.name,b):n.value=b}}),d=o.computed(()=>t.validation??null),c=o.computed(()=>({...a?a.locales.value[a.locale.value]:{},...t.validationMessages??{}})),y=o.computed({get:()=>s?s.getFields():{},set:()=>{}}),l=Xt(u,{rules:d,messages:c,fields:y}),f=o.ref(!1),m=o.ref(!1),i=o.ref([]),p=o.computed(()=>u.value??null),g=o.computed(()=>l.isValid.value&&i.value.length===0),$=o.computed(()=>[...l.errors.value,...i.value]),h=o.computed(()=>$.value[0]??null),A=o.toValue(u),v=t.id??r,M=`${v}-error`,w=`${v}-help`,W=b=>{i.value=Array.isArray(b)?b:[b]},N=()=>{u.value=A,f.value=!1,m.value=!1,i.value=[],l.reset()};o.watch(()=>t.error,b=>{b?i.value=Array.isArray(b)?b:[b]:i.value=[]},{immediate:!0});const D=o.computed(()=>({id:v,name:t.name,modelValue:u.value,"aria-invalid":!!h.value,"aria-describedby":h.value?`${M} ${w}`:w,"aria-errormessage":h.value?M:void 0,"onUpdate:modelValue":b=>{u.value=b,!m.value&&b!==A&&(m.value=!0)},onBlur:()=>{f.value||(f.value=!0,l.validate())}})),S={for:v},F={id:M,role:"alert","aria-live":"polite"},x={id:w};return o.onMounted(()=>{s&&s.addField(t.name,{value:p,isValid:g,isTouched:f,isDirty:m,error:h,errors:$,setErrors:W,reset:N,validate:l.validate})}),o.onUnmounted(()=>{s&&s.removeField(t.name)}),en({inputValue:u,inputProps:D,labelProps:S,helpProps:x,errorProps:F,isValid:g,isTouched:f,isDirty:m,error:h,errors:$,validate:l.validate,reset:N}),(b,on)=>(o.openBlock(),o.createElementBlock("div",null,[o.renderSlot(b.$slots,"default",o.normalizeProps(o.guardReactiveProps({inputValue:u.value,inputProps:D.value,labelProps:S,helpProps:x,errorProps:F,isValid:g.value,isTouched:f.value,isDirty:m.value,error:h.value,errors:$.value,validate:o.unref(l).validate,reset:N})))]))}});function rn(){const e=T();if(!e)throw new Error("[Valiform] useLocale() must be used inside a component with FormsPlugin installed.");return{locale:e.locale,locales:e.locales,setLocale:e.setLocale}}const sn={required:"Este campo es obligatorio",email:"Por favor ingresa un email válido",min:({value:e})=>`Debe ser al menos ${e}`,max:({value:e})=>`Debe ser como máximo ${e}`,matches:"El formato no es válido",number:"Debe ser un número válido",accepted:"Debe ser aceptado",alpha:"Debe contener solo caracteres alfabéticos",alphanumeric:"Debe contener solo letras y números",alphaSpaces:"Debe contener solo letras y espacios",between:({min:e,max:t})=>`Debe estar entre ${e} y ${t}`,confirm:({fieldName:e})=>`Debe coincidir con ${e}`,containsAlpha:"Debe contener al menos una letra",containsAlphanumeric:"Debe contener al menos una letra o número",containsAlphaSpaces:"Debe contener al menos una letra o espacio",containsLowercase:"Debe contener al menos una letra minúscula",containsNumeric:"Debe contener al menos un número",containsSymbol:"Debe contener al menos un símbolo",containsUppercase:"Debe contener al menos una letra mayúscula",dateAfter:({date:e})=>e?`Debe ser posterior a ${e}`:"Debe ser posterior a hoy",dateAfterOrEqual:({date:e})=>e?`Debe ser posterior o igual a ${e}`:"Debe ser posterior o igual a hoy",dateBefore:({date:e})=>e?`Debe ser anterior a ${e}`:"Debe ser anterior a hoy",dateBeforeOrEqual:({date:e})=>e?`Debe ser anterior o igual a ${e}`:"Debe ser anterior o igual a hoy",dateBetween:({startDate:e,endDate:t})=>`Debe estar entre ${e} y ${t}`,dateFormat:({format:e})=>`Debe coincidir con el formato ${e}`,endsWith:({suffix:e})=>Array.isArray(e)?`Debe terminar con uno de: ${e.map(t=>`"${t}"`).join(", ")}`:`Debe terminar con "${e}"`,is:({allowedValues:e})=>`Debe ser uno de: ${Array.isArray(e)?e.join(", "):e}`,length:({value:e,min:t,max:n})=>t!==void 0&&n!==void 0?`Debe tener entre ${t} y ${n} caracteres`:e!==void 0?`Debe tener exactamente ${e} caracteres`:"Longitud inválida",lowercase:"Debe contener solo caracteres en minúscula",not:({disallowedValues:e})=>`No debe ser uno de: ${Array.isArray(e)?e.join(", "):e}`,startsWith:({prefix:e})=>Array.isArray(e)?`Debe comenzar con uno de: ${e.join(", ")}`:`Debe comenzar con "${e}"`,symbol:"Debe contener solo símbolos",uppercase:"Debe contener solo caracteres en mayúscula",url:"Debe ser una URL válida"};exports.Field=nn;exports.Form=kt;exports.FormsPlugin=Lt;exports.en=q;exports.es=sn;exports.useFieldContext=tn;exports.useFormContext=It;exports.useLocale=rn;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("vue"),C=Symbol("locale-context"),q=(e=null)=>{const t=o.inject(C,e);if(!t&&t!==null)throw new Error("Context with localeContextKey not found");return t},E={required:"This field is required",email:"Please enter a valid email address",min:({value:e})=>`Must be at least ${e}`,max:({value:e})=>`Must be at most ${e}`,matches:"Format is not valid",number:"Must be a valid number",accepted:"Must be accepted",alpha:"Must contain only alphabetical characters",alphanumeric:"Must contain only letters and numbers",alphaSpaces:"Must contain only letters and spaces",between:({min:e,max:t})=>`Must be between ${e} and ${t}`,confirm:({fieldName:e})=>`Must match ${e}`,containsAlpha:"Must contain at least one letter",containsAlphanumeric:"Must contain at least one letter or number",containsAlphaSpaces:"Must contain at least one letter or space",containsLowercase:"Must contain at least one lowercase letter",containsNumeric:"Must contain at least one number",containsSymbol:"Must contain at least one symbol",containsUppercase:"Must contain at least one uppercase letter",dateAfter:({date:e})=>e?`Must be after ${e}`:"Must be after today",dateAfterOrEqual:({date:e})=>e?`Must be after or equal to ${e}`:"Must be after or equal to today",dateBefore:({date:e})=>e?`Must be before ${e}`:"Must be before today",dateBeforeOrEqual:({date:e})=>e?`Must be before or equal to ${e}`:"Must be before or equal to today",dateBetween:({startDate:e,endDate:t})=>`Must be between ${e} and ${t}`,dateFormat:({format:e})=>`Must match the format ${e}`,endsWith:({suffix:e})=>Array.isArray(e)?`Must end with one of: ${e.map(t=>`"${t}"`).join(", ")}`:`Must end with "${e}"`,is:({allowedValues:e})=>`Must be one of: ${Array.isArray(e)?e.join(", "):e}`,length:({value:e,min:t,max:n})=>t!==void 0&&n!==void 0?`Must be between ${t} and ${n} characters`:e!==void 0?`Must be exactly ${e} characters`:"Invalid length",lowercase:"Must contain only lowercase characters",not:({disallowedValues:e})=>`Must not be one of: ${Array.isArray(e)?e.join(", "):e}`,startsWith:({prefix:e})=>Array.isArray(e)?`Must start with one of: ${e.join(", ")}`:`Must start with "${e}"`,symbol:"Must contain only symbols",uppercase:"Must contain only uppercase characters",url:"Must be a valid URL"},B=o.shallowRef(new Map),_=(e,t)=>{B.value.set(e,t)},j=e=>{Object.entries(e).forEach(([t,n])=>{_(t,n)})},z=e=>B.value.get(e);function I(e){const t=e.accepted;return typeof t=="function"?t({}):t??"Must be accepted"}function U(e){return e?["yes","on","1","true"].includes(String(e).toLowerCase()):!1}function k(e,t={}){const{messages:n={}}=t;return U(e)?!0:I(n)}function K(e){const t=e.alpha;return typeof t=="function"?t({}):t??"Must contain only alphabetical characters"}function Z(e){return e?/^[a-zA-Z]+$/.test(String(e)):!0}function Y(e,t={}){const{messages:n={}}=t;return Z(e)?!0:K(n)}function G(e){const t=e.alphanumeric;return typeof t=="function"?t({}):t??"Must contain only letters and numbers"}function H(e){return e?/^[a-zA-Z0-9]+$/.test(String(e)):!0}function J(e,t={}){const{messages:n={}}=t;return H(e)?!0:G(n)}function Q(e){const t=e.alphaSpaces;return typeof t=="function"?t({}):t??"Must contain only letters and spaces"}function X(e){return e?/^[a-zA-Z\s]+$/.test(String(e)):!0}function ee(e,t={}){const{messages:n={}}=t;return X(e)?!0:Q(n)}function te(e,t,n){const r=e.between;return typeof r=="function"?r({min:t,max:n}):r??`Must be between ${t} and ${n}`}function ne(e,t,n){if(!e&&e!==0)return!0;const r=Number(e);if(isNaN(r))return!1;const s=Number(t),a=Number(n);return isNaN(s)||isNaN(a)?!1:r>=s&&r<=a}function re(e,t={}){const{args:n=[],messages:r={}}=t,[s,a]=n;return ne(e,s,a)?!0:te(r,s,a)}function se(e,t){const n=e.confirm;return typeof n=="function"?n({fieldName:t}):n??`Must match ${t}`}function oe(e,t,n){var r;return e?n?e===((r=n[t])==null?void 0:r.value):!1:!0}function ae(e,t={}){const{args:n=[],messages:r={},fields:s={}}=t,[a]=n;return oe(e,a,s)?!0:se(r,a)}function ue(e){const t=e.containsAlpha;return typeof t=="function"?t({}):t??"Must contain at least one letter"}function ie(e){return e?/[a-zA-Z]/.test(String(e)):!0}function ce(e,t={}){const{messages:n={}}=t;return ie(e)?!0:ue(n)}function le(e){const t=e.containsAlphanumeric;return typeof t=="function"?t({}):t??"Must contain at least one letter or number"}function fe(e){return e?/[a-zA-Z0-9]/.test(String(e)):!0}function me(e,t={}){const{messages:n={}}=t;return fe(e)?!0:le(n)}function de(e){const t=e.containsAlphaSpaces;return typeof t=="function"?t({}):t??"Must contain at least one letter or space"}function ge(e){return e?/[a-zA-Z\s]/.test(String(e)):!0}function pe(e,t={}){const{messages:n={}}=t;return ge(e)?!0:de(n)}function be(e){const t=e.containsLowercase;return typeof t=="function"?t({}):t??"Must contain at least one lowercase letter"}function ye(e){return e?/[a-z]/.test(String(e)):!0}function $e(e,t={}){const{messages:n={}}=t;return ye(e)?!0:be(n)}function he(e){const t=e.containsNumeric;return typeof t=="function"?t({}):t??"Must contain at least one number"}function ve(e){return e?/\d/.test(String(e)):!0}function Me(e,t={}){const{messages:n={}}=t;return ve(e)?!0:he(n)}function Ne(e){const t=e.containsSymbol;return typeof t=="function"?t({}):t??"Must contain at least one symbol"}function we(e){return e?/[^\w\s]/.test(String(e)):!0}function Ae(e,t={}){const{messages:n={}}=t;return we(e)?!0:Ne(n)}function Se(e){const t=e.containsUppercase;return typeof t=="function"?t({}):t??"Must contain at least one uppercase letter"}function De(e){return e?/[A-Z]/.test(String(e)):!0}function Fe(e,t={}){const{messages:n={}}=t;return De(e)?!0:Se(n)}function xe(e,t){const n=e.dateAfter;return typeof n=="function"?n({date:t}):n??(t?`Must be after ${t}`:"Must be after today")}function Ve(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n>r}function je(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Ve(e,s)?!0:xe(r,s)}function Pe(e,t){const n=e.dateAfterOrEqual;return typeof n=="function"?n({date:t}):n??(t?`Must be after or equal to ${t}`:"Must be after or equal to today")}function Te(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n>=r}function Ce(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Te(e,s)?!0:Pe(r,s)}function qe(e,t){const n=e.dateBefore;return typeof n=="function"?n({date:t}):n??(t?`Must be before ${t}`:"Must be before today")}function Ee(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n<r}function Be(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Ee(e,s)?!0:qe(r,s)}function Oe(e,t){const n=e.dateBeforeOrEqual;return typeof n=="function"?n({date:t}):n??(t?`Must be before or equal to ${t}`:"Must be before or equal to today")}function Re(e,t){if(!e)return!0;const n=new Date(String(e)),r=t?new Date(t):new Date;return!isNaN(n.getTime())&&!isNaN(r.getTime())&&n<=r}function Le(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return Re(e,s)?!0:Oe(r,s)}function We(e,t,n){const r=e.dateBetween;return typeof r=="function"?r({startDate:t,endDate:n}):r??`Must be between ${t} and ${n}`}function _e(e,t,n){if(!e)return!0;const r=new Date(String(e)),s=new Date(t),a=new Date(n);return!isNaN(r.getTime())&&!isNaN(s.getTime())&&!isNaN(a.getTime())&&r>=s&&r<=a}function ze(e,t={}){const{args:n=[],messages:r={}}=t,[s,a]=n;return _e(e,s,a)?!0:We(r,s,a)}const Ie=e=>{const t=e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),n={YYYY:"\\d{4}",YY:"\\d{2}",MM:"(0[1-9]|1[012])",M:"([1-9]|1[012])",DD:"([012][0-9]|3[01])",D:"([012]?[0-9]|3[01])"};let r=t;return Object.keys(n).forEach(s=>{r=r.replace(new RegExp(s,"g"),n[s])}),new RegExp(`^${r}$`)};function Ue(e,t){const n=e.dateFormat;return typeof n=="function"?n({format:t}):n??`Must match the format ${t}`}function ke(e,t){return e?t&&typeof t=="string"?Ie(t).test(String(e)):!isNaN(Date.parse(String(e))):!0}function Ke(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return ke(e,s)?!0:Ue(r,s)}function Ze(e){const t=e.email;return typeof t=="function"?t({}):t??"Please enter a valid email address"}function Ye(e){return e?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(e)):!0}function Ge(e,t={}){const{messages:n={}}=t;return Ye(e)?!0:Ze(n)}function He(e,t){const n=e.endsWith;return typeof n=="function"?n({suffix:t.length===1?t[0]:t}):n??`Must end with: ${t.join(", ")}`}function Je(e,...t){if(!e)return!0;const n=String(e);return t.some(r=>n.endsWith(r))}function Qe(e,t={}){const{args:n=[],messages:r={}}=t;return Je(e,...n)?!0:He(r,n)}function Xe(e,t){const n=e.is;return typeof n=="function"?n({allowedValues:t}):n??`Must be one of: ${t.join(", ")}`}function et(e,...t){return!e&&e!==0&&e!==!1?!0:t.includes(String(e))}function tt(e,t={}){const{args:n=[],messages:r={}}=t;return et(e,...n)?!0:Xe(r,n)}function nt(e,t,n){const r=e.length;return n!==void 0?typeof r=="function"?r({min:t,max:n}):r??`Must be between ${t} and ${n} characters`:typeof r=="function"?r({value:t}):r??`Must be exactly ${t} characters`}function rt(e,t,n){if(!e&&e!==0)return!0;let r=0;if(typeof e=="string")r=e.length;else if(Array.isArray(e))r=e.length;else if(typeof e=="object"&&e!==null)r=Object.keys(e).length;else return!1;if(n!==void 0){const a=Number(t),u=Number(n);return!isNaN(a)&&!isNaN(u)&&r>=a&&r<=u}const s=Number(t);return!isNaN(s)&&r===s}function st(e,t={}){const{args:n=[],messages:r={}}=t,[s,a]=n;return rt(e,s,a)?!0:nt(r,s,a)}function ot(e){const t=e.lowercase;return typeof t=="function"?t({}):t??"Must contain only lowercase characters"}function at(e){return e?/^[a-z]+$/.test(String(e)):!0}function ut(e,t={}){const{messages:n={}}=t;return at(e)?!0:ot(n)}function it(e,t,n){const r=t.matches;return typeof r=="function"?r({value:e,pattern:n}):r??"Format is not valid"}function ct(e,t){if(!e)return!0;if(!t)return!1;try{if(t.startsWith("/")&&t.includes("/",1)){const n=t.lastIndexOf("/"),r=t.slice(1,n),s=t.slice(n+1);return new RegExp(r,s).test(String(e))}return String(e)===t}catch{return!1}}function lt(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return ct(e,s)?!0:it(e,r,s)}function ft(e,t){const n=e.max;return typeof n=="function"?n({value:t}):n??`Must be at most ${t}`}function mt(e,t){if(!e&&e!==0)return!0;const n=Number(t);if(isNaN(n))return!1;if(typeof e=="number")return e<=n;if(typeof e=="string"){const r=Number(e);return isNaN(r)?e.length<=n:r<=n}return Array.isArray(e)?e.length<=n:!1}function dt(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return mt(e,s)?!0:ft(r,s)}function gt(e,t){const n=e.min;return typeof n=="function"?n({value:t}):n??`Must be at least ${t}`}function pt(e,t){if(!e&&e!==0)return!0;const n=Number(t);if(isNaN(n))return!1;if(typeof e=="number")return e>=n;if(typeof e=="string"){const r=Number(e);return isNaN(r)?e.length>=n:r>=n}return Array.isArray(e)?e.length>=n:!1}function bt(e,t={}){const{args:n=[],messages:r={}}=t,[s]=n;return pt(e,s)?!0:gt(r,s)}function yt(e,t){const n=e.not;return typeof n=="function"?n({disallowedValues:t}):n??`Must not be one of: ${t.join(", ")}`}function $t(e,...t){return!e&&e!==0&&e!==!1?!0:!t.includes(String(e))}function ht(e,t={}){const{args:n=[],messages:r={}}=t;return $t(e,...n)?!0:yt(r,n)}function vt(e){const t=e.number;return typeof t=="function"?t({}):t??"Must be a valid number"}function Mt(e){if(e==null||e==="")return!0;if(Number.isNaN(e))return!1;const t=Number(e);return!isNaN(t)&&isFinite(t)}function Nt(e,t={}){const{messages:n={}}=t;return Mt(e)?!0:vt(n)}function wt(e){const t=e.required;return typeof t=="function"?t({}):t??"This field is required"}function At(e){return e==null||e===""?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:e===0?!0:!!e}function St(e,t={}){const{messages:n={}}=t;return At(e)?!0:wt(n)}function Dt(e,t){const n=e.startsWith;return typeof n=="function"?n({prefix:t.length===1?t[0]:t}):n??`Must start with: ${t.join(", ")}`}function Ft(e,...t){if(!e)return!0;const n=String(e);return t.some(r=>n.startsWith(r))}function xt(e,t={}){const{args:n=[],messages:r={}}=t;return Ft(e,...n)?!0:Dt(r,n)}function Vt(e){const t=e.symbol;return typeof t=="function"?t({}):t??"Must contain only symbols"}function jt(e){return e?/^[^\w\s]+$/.test(String(e)):!0}function Pt(e,t={}){const{messages:n={}}=t;return jt(e)?!0:Vt(n)}function Tt(e){const t=e.uppercase;return typeof t=="function"?t({}):t??"Must contain only uppercase characters"}function Ct(e){return e?/^[A-Z]+$/.test(String(e)):!0}function qt(e,t={}){const{messages:n={}}=t;return Ct(e)?!0:Tt(n)}function Et(e){const t=e.url;return typeof t=="function"?t({}):t??"Must be a valid URL"}function Bt(e){if(!e)return!0;try{const t=new URL(String(e));return["http:","https:","ftp:","ftps:"].includes(t.protocol)}catch{return!1}}function Ot(e,t={}){const{messages:n={}}=t;return Bt(e)?!0:Et(n)}const Rt=Object.freeze(Object.defineProperty({__proto__:null,accepted:k,alpha:Y,alphaSpaces:ee,alphanumeric:J,between:re,confirm:ae,containsAlpha:ce,containsAlphaSpaces:pe,containsAlphanumeric:me,containsLowercase:$e,containsNumeric:Me,containsSymbol:Ae,containsUppercase:Fe,dateAfter:je,dateAfterOrEqual:Ce,dateBefore:Be,dateBeforeOrEqual:Le,dateBetween:ze,dateFormat:Ke,email:Ge,endsWith:Qe,is:tt,length:st,lowercase:ut,matches:lt,max:dt,min:bt,not:ht,number:Nt,required:St,startsWith:xt,symbol:Pt,uppercase:qt,url:Ot},Symbol.toStringTag,{value:"Module"})),Lt={install(e,t={}){j(Rt),t.rules&&j(t.rules);const n=o.isRef(t.locale)?t.locale:o.ref(t.locale??"en"),r={en:E};t.locales&&Object.keys(t.locales).forEach(a=>{r[a]={...r[a]??{},...t.locales[a]}});const s=o.shallowRef(r);e.provide(C,{locale:o.readonly(n),locales:o.readonly(s),setLocale:a=>{s.value[a]?n.value=a:console.warn(`Locale "${a}" not available.`)}})}},O=Symbol("form-state-context"),Wt=e=>{o.provide(O,e)},_t=(e=null)=>{const t=o.inject(O,e);if(!t&&t!==null)throw new Error("Context with formStateContextKey not found");return t},R=Symbol("form-context"),zt=e=>{o.provide(R,e)},It=(e=null)=>{const t=o.inject(R,e);if(!t&&t!==null)throw new Error("Context with formContextKey not found");return t};function Ut(e,t){if(!(!e||!t))return t.split(".").reduce((n,r)=>n==null?void 0:n[r],e)}function kt(e,t,n){if(!e||!t)return e;const r=t.split("."),s=r.pop(),a=r.reduce((u,d,c)=>{if(u[d]===null||u[d]===void 0){const y=r[c+1]||s;u[d]=/^\d+$/.test(y)?[]:{}}return u[d]},e);return a[s]=n,e}const Kt=o.defineComponent({__name:"Form",props:{modelValue:{default:()=>({})},modelModifiers:{}},emits:o.mergeModels(["submit"],["update:modelValue"]),setup(e,{emit:t}){const n=t,r=o.useModel(e,"modelValue");o.isReactive(r.value)||(r.value=o.reactive(r.value??{}));const s=o.ref({}),a=o.ref([]),u=o.computed(()=>r.value),d=o.computed(()=>a.value[0]??null),c=o.computed(()=>Object.keys(s.value).every(i=>s.value[i].isValid)),y=()=>{Object.keys(s.value).forEach(i=>{var p,g;(g=(p=s.value[i]).validate)==null||g.call(p)})},l=()=>{y(),c.value&&(a.value=[],n("submit",r.value,{setErrors:f,reset:m}))},f=(...i)=>{var p;if(i.length===1){const g=i[0];if(typeof g=="object"&&!Array.isArray(g)&&g!==null){Object.keys(g).forEach($=>{f($,g[$])});return}a.value=Array.isArray(g)?g:[g]}else if(i.length===2){const[g,$]=i;(p=s.value[g])==null||p.setErrors($)}},m=()=>{a.value=[],Object.keys(s.value).forEach(i=>{s.value[i].reset()})};return Wt({getFields(){return s.value},getField(i){return s.value[i]},addField(i,p){s.value[i]=p},removeField(i){delete s.value[i]},setFieldValue(i,p){kt(r.value,i,p)},getFieldValue(i){return Ut(r.value,i)}}),zt({values:u,isValid:c,error:d,errors:a,fields:s,reset:m,setErrors:f,validate:y}),(i,p)=>(o.openBlock(),o.createElementBlock("form",{onSubmit:o.withModifiers(l,["prevent"])},[o.renderSlot(i.$slots,"default",o.normalizeProps(o.guardReactiveProps({isValid:c.value,error:d.value,errors:a.value,values:u.value,fields:s.value,reset:m,setErrors:f,validate:y})))],32))}});function L(e){if(!e||typeof e!="string")return{};const t=e.split("|").filter(Boolean),n={};for(const r of t){const[s,...a]=r.split(":"),u=s.trim();if(a.length===0)n[u]=!0;else{const c=a.join(":").split(",").map(y=>y.trim());n[u]=c.length===1?c[0]:c}}return n}const Zt=(e,t,n={},r={})=>{if(!t)return!0;const s=L(t),a=[];for(const[u,d]of Object.entries(s)){const c=z(u);if(c){const l={args:d===!0?[]:Array.isArray(d)?d:[d],messages:n,fields:r},f=c(e,l);f!==!0&&a.push(f??"Invalid value")}else console.warn(`[Forms] Validation rule "${u}" not found.`)}return a.length===0?!0:a},Yt=(e,t)=>{const n=t(e);return n===!0?!0:typeof n=="string"?[n]:Array.isArray(n)?n:!!n?!0:["Invalid value"]};typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const P=()=>{};function Gt(e,t){function n(...r){return new Promise((s,a)=>{Promise.resolve(e(()=>t.apply(this,r),{fn:t,thisArg:this,args:r})).then(s).catch(a)})}return n}const Ht=e=>e();function Jt(e,t={}){let n,r,s=P;const a=c=>{clearTimeout(c),s(),s=P};let u;return c=>{const y=o.toValue(e),l=o.toValue(t.maxWait);return n&&a(n),y<=0||l!==void 0&&l<=0?(r&&(a(r),r=void 0),Promise.resolve(c())):new Promise((f,m)=>{s=t.rejectOnCancel?m:f,u=c,l&&!r&&(r=setTimeout(()=>{n&&a(n),r=void 0,f(u())},l)),n=setTimeout(()=>{r&&a(r),r=void 0,f(c())},y)})}}function Qt(e,t,n={}){const{eventFilter:r=Ht,...s}=n;return o.watch(e,Gt(r,t),s)}function T(e,t,n={}){const{debounce:r=0,maxWait:s=void 0,...a}=n;return Qt(e,t,{...a,eventFilter:Jt(r,{maxWait:s})})}function Xt(e,t={}){const n=o.ref(!0),r=o.ref(!1),s=o.ref([]),a=o.ref(null),u=o.computed(()=>o.toValue(t.rules)??null),d=o.computed(()=>o.toValue(t.messages)??{}),c=o.computed(()=>o.toValue(t.fields)??{}),y=o.computed(()=>{if(!u.value||typeof u.value!="string")return null;const i=L(u.value).confirm;if(!i||i===!0)return null;const p=c.value[i];return(p==null?void 0:p.value)??null}),l=()=>{let m;return typeof u.value=="function"?m=Yt(o.toValue(e),u.value):m=Zt(o.toValue(e),u.value,d.value,c.value),m===!0?(n.value=!0,s.value=[],!0):Array.isArray(m)?(n.value=!1,s.value=m,!1):m},f=()=>{a.value&&clearTimeout(a.value),r.value=!0,n.value=!0,s.value=[],a.value=setTimeout(()=>{r.value=!1,a.value=null},1e3)};return T(()=>o.toValue(e),()=>{r.value||l()},{debounce:300}),T(()=>o.toValue(y),()=>{r.value||o.toValue(e)&&l()},{debounce:300}),{validate:l,reset:f,isValid:o.readonly(n),errors:o.readonly(s)}}const A=Symbol("field-context"),en=e=>{o.provide(A,e)};function tn(e){if(e===void 0){const t=o.inject(A);if(!t)throw new Error("useFieldContext() must be called inside a Field component");return t}return o.inject(A,e)}const nn=o.defineComponent({__name:"Field",props:o.mergeModels({id:{},name:{},validation:{type:[String,Function,null]},validationMessages:{},error:{}},{modelValue:{},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const t=e,n=o.useModel(e,"modelValue"),r=o.useId(),s=_t(),a=q(),u=o.computed({get:()=>s?s.getFieldValue(t.name):n.value,set:b=>{s?s.setFieldValue(t.name,b):n.value=b}}),d=o.computed(()=>t.validation??null),c=o.computed(()=>({...a?a.locales.value[a.locale.value]:{},...t.validationMessages??{}})),y=o.computed({get:()=>s?s.getFields():{},set:()=>{}}),l=Xt(u,{rules:d,messages:c,fields:y}),f=o.ref(!1),m=o.ref(!1),i=o.ref([]),p=o.computed(()=>u.value??null),g=o.computed(()=>l.isValid.value&&i.value.length===0),$=o.computed(()=>[...l.errors.value,...i.value]),h=o.computed(()=>$.value[0]??null),S=o.toValue(u),v=t.id??r,M=`${v}-error`,N=`${v}-help`,W=b=>{i.value=Array.isArray(b)?b:[b]},w=()=>{u.value=S,f.value=!1,m.value=!1,i.value=[],l.reset()};o.watch(()=>t.error,b=>{b?i.value=Array.isArray(b)?b:[b]:i.value=[]},{immediate:!0});const D=o.computed(()=>({id:v,name:t.name,modelValue:u.value,"aria-invalid":!!h.value,"aria-describedby":h.value?`${M} ${N}`:N,"aria-errormessage":h.value?M:void 0,"onUpdate:modelValue":b=>{u.value=b,!m.value&&b!==S&&(m.value=!0)},onBlur:()=>{f.value||(f.value=!0,l.validate())}})),F={for:v},x={id:M,role:"alert","aria-live":"polite"},V={id:N};return o.onMounted(()=>{s&&s.addField(t.name,{value:p,isValid:g,isTouched:f,isDirty:m,error:h,errors:$,setErrors:W,reset:w,validate:l.validate})}),o.onUnmounted(()=>{s&&s.removeField(t.name)}),en({inputValue:u,inputProps:D,labelProps:F,helpProps:V,errorProps:x,isValid:g,isTouched:f,isDirty:m,error:h,errors:$,validate:l.validate,reset:w}),(b,on)=>(o.openBlock(),o.createElementBlock("div",null,[o.renderSlot(b.$slots,"default",o.normalizeProps(o.guardReactiveProps({inputValue:u.value,inputProps:D.value,labelProps:F,helpProps:V,errorProps:x,isValid:g.value,isTouched:f.value,isDirty:m.value,error:h.value,errors:$.value,validate:o.unref(l).validate,reset:w})))]))}});function rn(){const e=q();if(!e)throw new Error("[Valiform] useLocale() must be used inside a component with FormsPlugin installed.");return{locale:e.locale,locales:e.locales,setLocale:e.setLocale}}const sn={required:"Este campo es obligatorio",email:"Por favor ingresa un email válido",min:({value:e})=>`Debe ser al menos ${e}`,max:({value:e})=>`Debe ser como máximo ${e}`,matches:"El formato no es válido",number:"Debe ser un número válido",accepted:"Debe ser aceptado",alpha:"Debe contener solo caracteres alfabéticos",alphanumeric:"Debe contener solo letras y números",alphaSpaces:"Debe contener solo letras y espacios",between:({min:e,max:t})=>`Debe estar entre ${e} y ${t}`,confirm:({fieldName:e})=>`Debe coincidir con ${e}`,containsAlpha:"Debe contener al menos una letra",containsAlphanumeric:"Debe contener al menos una letra o número",containsAlphaSpaces:"Debe contener al menos una letra o espacio",containsLowercase:"Debe contener al menos una letra minúscula",containsNumeric:"Debe contener al menos un número",containsSymbol:"Debe contener al menos un símbolo",containsUppercase:"Debe contener al menos una letra mayúscula",dateAfter:({date:e})=>e?`Debe ser posterior a ${e}`:"Debe ser posterior a hoy",dateAfterOrEqual:({date:e})=>e?`Debe ser posterior o igual a ${e}`:"Debe ser posterior o igual a hoy",dateBefore:({date:e})=>e?`Debe ser anterior a ${e}`:"Debe ser anterior a hoy",dateBeforeOrEqual:({date:e})=>e?`Debe ser anterior o igual a ${e}`:"Debe ser anterior o igual a hoy",dateBetween:({startDate:e,endDate:t})=>`Debe estar entre ${e} y ${t}`,dateFormat:({format:e})=>`Debe coincidir con el formato ${e}`,endsWith:({suffix:e})=>Array.isArray(e)?`Debe terminar con uno de: ${e.map(t=>`"${t}"`).join(", ")}`:`Debe terminar con "${e}"`,is:({allowedValues:e})=>`Debe ser uno de: ${Array.isArray(e)?e.join(", "):e}`,length:({value:e,min:t,max:n})=>t!==void 0&&n!==void 0?`Debe tener entre ${t} y ${n} caracteres`:e!==void 0?`Debe tener exactamente ${e} caracteres`:"Longitud inválida",lowercase:"Debe contener solo caracteres en minúscula",not:({disallowedValues:e})=>`No debe ser uno de: ${Array.isArray(e)?e.join(", "):e}`,startsWith:({prefix:e})=>Array.isArray(e)?`Debe comenzar con uno de: ${e.join(", ")}`:`Debe comenzar con "${e}"`,symbol:"Debe contener solo símbolos",uppercase:"Debe contener solo caracteres en mayúscula",url:"Debe ser una URL válida"};exports.Field=nn;exports.Form=Kt;exports.FormsPlugin=Lt;exports.en=E;exports.es=sn;exports.useFieldContext=tn;exports.useFormContext=It;exports.useLocale=rn;
|
package/dist/index.d.ts
CHANGED
|
@@ -4,5 +4,6 @@ export { default as Field } from './src/components/Field.vue';
|
|
|
4
4
|
export { useLocale } from './src/composables/useLocale';
|
|
5
5
|
export { useFormContext } from './src/context/useFormContext';
|
|
6
6
|
export { useFieldContext } from './src/context/useFieldContext';
|
|
7
|
+
export type { FieldContext, FieldState, FormContext, InputProps, RuleFunction, FormsPluginOptions } from './src/types';
|
|
7
8
|
export { en } from './src/locales/en';
|
|
8
9
|
export { es } from './src/locales/es';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { inject as
|
|
2
|
-
const
|
|
3
|
-
const t =
|
|
1
|
+
import { inject as N, shallowRef as R, isRef as te, ref as h, readonly as A, provide as j, defineComponent as W, useModel as L, isReactive as ne, reactive as re, computed as b, openBlock as _, createElementBlock as z, withModifiers as se, renderSlot as I, normalizeProps as U, guardReactiveProps as K, mergeModels as Z, watch as k, toValue as $, useId as oe, onMounted as ae, onUnmounted as ue, unref as ie } from "vue";
|
|
2
|
+
const Y = Symbol("locale-context"), G = (e = null) => {
|
|
3
|
+
const t = N(Y, e);
|
|
4
4
|
if (!t && t !== null)
|
|
5
5
|
throw new Error("Context with localeContextKey not found");
|
|
6
6
|
return t;
|
|
@@ -39,13 +39,13 @@ const k = Symbol("locale-context"), Y = (e = null) => {
|
|
|
39
39
|
symbol: "Must contain only symbols",
|
|
40
40
|
uppercase: "Must contain only uppercase characters",
|
|
41
41
|
url: "Must be a valid URL"
|
|
42
|
-
},
|
|
43
|
-
|
|
44
|
-
},
|
|
42
|
+
}, H = R(/* @__PURE__ */ new Map()), le = (e, t) => {
|
|
43
|
+
H.value.set(e, t);
|
|
44
|
+
}, E = (e) => {
|
|
45
45
|
Object.entries(e).forEach(([t, n]) => {
|
|
46
46
|
le(t, n);
|
|
47
47
|
});
|
|
48
|
-
}, fe = (e) =>
|
|
48
|
+
}, fe = (e) => H.value.get(e);
|
|
49
49
|
function me(e) {
|
|
50
50
|
const t = e.accepted;
|
|
51
51
|
return typeof t == "function" ? t({}) : t ?? "Must be accepted";
|
|
@@ -128,16 +128,16 @@ function qe(e, t = {}) {
|
|
|
128
128
|
const { messages: n = {} } = t;
|
|
129
129
|
return Ve(e) ? !0 : Te(n);
|
|
130
130
|
}
|
|
131
|
-
function
|
|
131
|
+
function Pe(e) {
|
|
132
132
|
const t = e.containsAlphanumeric;
|
|
133
133
|
return typeof t == "function" ? t({}) : t ?? "Must contain at least one letter or number";
|
|
134
134
|
}
|
|
135
|
-
function
|
|
135
|
+
function Ce(e) {
|
|
136
136
|
return e ? /[a-zA-Z0-9]/.test(String(e)) : !0;
|
|
137
137
|
}
|
|
138
138
|
function Ee(e, t = {}) {
|
|
139
139
|
const { messages: n = {} } = t;
|
|
140
|
-
return
|
|
140
|
+
return Ce(e) ? !0 : Pe(n);
|
|
141
141
|
}
|
|
142
142
|
function Oe(e) {
|
|
143
143
|
const t = e.containsAlphaSpaces;
|
|
@@ -168,11 +168,11 @@ function ze(e) {
|
|
|
168
168
|
function Ie(e) {
|
|
169
169
|
return e ? /\d/.test(String(e)) : !0;
|
|
170
170
|
}
|
|
171
|
-
function
|
|
171
|
+
function Ue(e, t = {}) {
|
|
172
172
|
const { messages: n = {} } = t;
|
|
173
173
|
return Ie(e) ? !0 : ze(n);
|
|
174
174
|
}
|
|
175
|
-
function
|
|
175
|
+
function Ke(e) {
|
|
176
176
|
const t = e.containsSymbol;
|
|
177
177
|
return typeof t == "function" ? t({}) : t ?? "Must contain at least one symbol";
|
|
178
178
|
}
|
|
@@ -181,7 +181,7 @@ function Ze(e) {
|
|
|
181
181
|
}
|
|
182
182
|
function ke(e, t = {}) {
|
|
183
183
|
const { messages: n = {} } = t;
|
|
184
|
-
return Ze(e) ? !0 :
|
|
184
|
+
return Ze(e) ? !0 : Ke(n);
|
|
185
185
|
}
|
|
186
186
|
function Ye(e) {
|
|
187
187
|
const t = e.containsUppercase;
|
|
@@ -373,11 +373,11 @@ function qt(e, t) {
|
|
|
373
373
|
return !1;
|
|
374
374
|
}
|
|
375
375
|
}
|
|
376
|
-
function
|
|
376
|
+
function Pt(e, t = {}) {
|
|
377
377
|
const { args: n = [], messages: r = {} } = t, [s] = n;
|
|
378
378
|
return qt(e, s) ? !0 : Vt(e, r, s);
|
|
379
379
|
}
|
|
380
|
-
function
|
|
380
|
+
function Ct(e, t) {
|
|
381
381
|
const n = e.max;
|
|
382
382
|
return typeof n == "function" ? n({ value: t }) : n ?? `Must be at most ${t}`;
|
|
383
383
|
}
|
|
@@ -394,7 +394,7 @@ function Et(e, t) {
|
|
|
394
394
|
}
|
|
395
395
|
function Ot(e, t = {}) {
|
|
396
396
|
const { args: n = [], messages: r = {} } = t, [s] = n;
|
|
397
|
-
return Et(e, s) ? !0 :
|
|
397
|
+
return Et(e, s) ? !0 : Ct(r, s);
|
|
398
398
|
}
|
|
399
399
|
function Bt(e, t) {
|
|
400
400
|
const n = e.min;
|
|
@@ -430,15 +430,15 @@ function It(e) {
|
|
|
430
430
|
const t = e.number;
|
|
431
431
|
return typeof t == "function" ? t({}) : t ?? "Must be a valid number";
|
|
432
432
|
}
|
|
433
|
-
function
|
|
433
|
+
function Ut(e) {
|
|
434
434
|
if (e == null || e === "") return !0;
|
|
435
435
|
if (Number.isNaN(e)) return !1;
|
|
436
436
|
const t = Number(e);
|
|
437
437
|
return !isNaN(t) && isFinite(t);
|
|
438
438
|
}
|
|
439
|
-
function
|
|
439
|
+
function Kt(e, t = {}) {
|
|
440
440
|
const { messages: n = {} } = t;
|
|
441
|
-
return
|
|
441
|
+
return Ut(e) ? !0 : It(n);
|
|
442
442
|
}
|
|
443
443
|
function Zt(e) {
|
|
444
444
|
const t = e.required;
|
|
@@ -515,7 +515,7 @@ const un = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
|
515
515
|
containsAlphaSpaces: Re,
|
|
516
516
|
containsAlphanumeric: Ee,
|
|
517
517
|
containsLowercase: _e,
|
|
518
|
-
containsNumeric:
|
|
518
|
+
containsNumeric: Ue,
|
|
519
519
|
containsSymbol: ke,
|
|
520
520
|
containsUppercase: He,
|
|
521
521
|
dateAfter: Xe,
|
|
@@ -529,11 +529,11 @@ const un = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
|
529
529
|
is: At,
|
|
530
530
|
length: Ft,
|
|
531
531
|
lowercase: Tt,
|
|
532
|
-
matches:
|
|
532
|
+
matches: Pt,
|
|
533
533
|
max: Ot,
|
|
534
534
|
min: Wt,
|
|
535
535
|
not: zt,
|
|
536
|
-
number:
|
|
536
|
+
number: Kt,
|
|
537
537
|
required: Yt,
|
|
538
538
|
startsWith: Jt,
|
|
539
539
|
symbol: en,
|
|
@@ -541,31 +541,31 @@ const un = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
|
541
541
|
url: an
|
|
542
542
|
}, Symbol.toStringTag, { value: "Module" })), An = {
|
|
543
543
|
install(e, t = {}) {
|
|
544
|
-
|
|
544
|
+
E(un), t.rules && E(t.rules);
|
|
545
545
|
const n = te(t.locale) ? t.locale : h(t.locale ?? "en"), r = { en: ce };
|
|
546
546
|
t.locales && Object.keys(t.locales).forEach((o) => {
|
|
547
547
|
r[o] = { ...r[o] ?? {}, ...t.locales[o] };
|
|
548
548
|
});
|
|
549
|
-
const s =
|
|
550
|
-
e.provide(
|
|
551
|
-
locale:
|
|
552
|
-
locales:
|
|
549
|
+
const s = R(r);
|
|
550
|
+
e.provide(Y, {
|
|
551
|
+
locale: A(n),
|
|
552
|
+
locales: A(s),
|
|
553
553
|
setLocale: (o) => {
|
|
554
554
|
s.value[o] ? n.value = o : console.warn(`Locale "${o}" not available.`);
|
|
555
555
|
}
|
|
556
556
|
});
|
|
557
557
|
}
|
|
558
|
-
},
|
|
559
|
-
|
|
558
|
+
}, J = Symbol("form-state-context"), cn = (e) => {
|
|
559
|
+
j(J, e);
|
|
560
560
|
}, ln = (e = null) => {
|
|
561
|
-
const t =
|
|
561
|
+
const t = N(J, e);
|
|
562
562
|
if (!t && t !== null)
|
|
563
563
|
throw new Error("Context with formStateContextKey not found");
|
|
564
564
|
return t;
|
|
565
|
-
},
|
|
566
|
-
|
|
565
|
+
}, Q = Symbol("form-context"), fn = (e) => {
|
|
566
|
+
j(Q, e);
|
|
567
567
|
}, Dn = (e = null) => {
|
|
568
|
-
const t =
|
|
568
|
+
const t = N(Q, e);
|
|
569
569
|
if (!t && t !== null)
|
|
570
570
|
throw new Error("Context with formContextKey not found");
|
|
571
571
|
return t;
|
|
@@ -585,7 +585,7 @@ function dn(e, t, n) {
|
|
|
585
585
|
}, e);
|
|
586
586
|
return o[s] = n, e;
|
|
587
587
|
}
|
|
588
|
-
const Sn = /* @__PURE__ */
|
|
588
|
+
const Sn = /* @__PURE__ */ W({
|
|
589
589
|
__name: "Form",
|
|
590
590
|
props: {
|
|
591
591
|
modelValue: {
|
|
@@ -593,9 +593,9 @@ const Sn = /* @__PURE__ */ R({
|
|
|
593
593
|
},
|
|
594
594
|
modelModifiers: {}
|
|
595
595
|
},
|
|
596
|
-
emits: /* @__PURE__ */
|
|
596
|
+
emits: /* @__PURE__ */ Z(["submit"], ["update:modelValue"]),
|
|
597
597
|
setup(e, { emit: t }) {
|
|
598
|
-
const n = t, r =
|
|
598
|
+
const n = t, r = L(e, "modelValue");
|
|
599
599
|
ne(r.value) || (r.value = re(r.value ?? {}));
|
|
600
600
|
const s = h({}), o = h([]), a = b(() => r.value), m = b(() => o.value[0] ?? null), i = b(
|
|
601
601
|
() => Object.keys(s.value).every((u) => s.value[u].isValid)
|
|
@@ -654,10 +654,10 @@ const Sn = /* @__PURE__ */ R({
|
|
|
654
654
|
reset: f,
|
|
655
655
|
setErrors: l,
|
|
656
656
|
validate: y
|
|
657
|
-
}), (u, g) => (
|
|
657
|
+
}), (u, g) => (_(), z("form", {
|
|
658
658
|
onSubmit: se(c, ["prevent"])
|
|
659
659
|
}, [
|
|
660
|
-
|
|
660
|
+
I(u.$slots, "default", U(K({
|
|
661
661
|
isValid: i.value,
|
|
662
662
|
error: m.value,
|
|
663
663
|
errors: o.value,
|
|
@@ -670,7 +670,7 @@ const Sn = /* @__PURE__ */ R({
|
|
|
670
670
|
], 32));
|
|
671
671
|
}
|
|
672
672
|
});
|
|
673
|
-
function
|
|
673
|
+
function X(e) {
|
|
674
674
|
if (!e || typeof e != "string")
|
|
675
675
|
return {};
|
|
676
676
|
const t = e.split("|").filter(Boolean), n = {};
|
|
@@ -687,7 +687,7 @@ function Q(e) {
|
|
|
687
687
|
}
|
|
688
688
|
const gn = (e, t, n = {}, r = {}) => {
|
|
689
689
|
if (!t) return !0;
|
|
690
|
-
const s =
|
|
690
|
+
const s = X(t), o = [];
|
|
691
691
|
for (const [a, m] of Object.entries(s)) {
|
|
692
692
|
const i = fe(a);
|
|
693
693
|
if (i) {
|
|
@@ -702,7 +702,7 @@ const gn = (e, t, n = {}, r = {}) => {
|
|
|
702
702
|
return n === !0 ? !0 : typeof n == "string" ? [n] : Array.isArray(n) ? n : !!n ? !0 : ["Invalid value"];
|
|
703
703
|
};
|
|
704
704
|
typeof WorkerGlobalScope < "u" && globalThis instanceof WorkerGlobalScope;
|
|
705
|
-
const
|
|
705
|
+
const O = () => {
|
|
706
706
|
};
|
|
707
707
|
function bn(e, t) {
|
|
708
708
|
function n(...r) {
|
|
@@ -718,9 +718,9 @@ function bn(e, t) {
|
|
|
718
718
|
}
|
|
719
719
|
const yn = (e) => e();
|
|
720
720
|
function $n(e, t = {}) {
|
|
721
|
-
let n, r, s =
|
|
721
|
+
let n, r, s = O;
|
|
722
722
|
const o = (i) => {
|
|
723
|
-
clearTimeout(i), s(), s =
|
|
723
|
+
clearTimeout(i), s(), s = O;
|
|
724
724
|
};
|
|
725
725
|
let a;
|
|
726
726
|
return (i) => {
|
|
@@ -736,9 +736,9 @@ function $n(e, t = {}) {
|
|
|
736
736
|
}
|
|
737
737
|
function hn(e, t, n = {}) {
|
|
738
738
|
const { eventFilter: r = yn, ...s } = n;
|
|
739
|
-
return
|
|
739
|
+
return k(e, bn(r, t), s);
|
|
740
740
|
}
|
|
741
|
-
function
|
|
741
|
+
function B(e, t, n = {}) {
|
|
742
742
|
const { debounce: r = 0, maxWait: s = void 0, ...o } = n;
|
|
743
743
|
return hn(e, t, {
|
|
744
744
|
...o,
|
|
@@ -748,7 +748,7 @@ function O(e, t, n = {}) {
|
|
|
748
748
|
function vn(e, t = {}) {
|
|
749
749
|
const n = h(!0), r = h(!1), s = h([]), o = h(null), a = b(() => $(t.rules) ?? null), m = b(() => $(t.messages) ?? {}), i = b(() => $(t.fields) ?? {}), y = b(() => {
|
|
750
750
|
if (!a.value || typeof a.value != "string") return null;
|
|
751
|
-
const u =
|
|
751
|
+
const u = X(a.value).confirm;
|
|
752
752
|
if (!u || u === !0) return null;
|
|
753
753
|
const g = i.value[u];
|
|
754
754
|
return (g == null ? void 0 : g.value) ?? null;
|
|
@@ -765,13 +765,13 @@ function vn(e, t = {}) {
|
|
|
765
765
|
r.value = !1, o.value = null;
|
|
766
766
|
}, 1e3);
|
|
767
767
|
};
|
|
768
|
-
return
|
|
768
|
+
return B(
|
|
769
769
|
() => $(e),
|
|
770
770
|
() => {
|
|
771
771
|
r.value || c();
|
|
772
772
|
},
|
|
773
773
|
{ debounce: 300 }
|
|
774
|
-
),
|
|
774
|
+
), B(
|
|
775
775
|
() => $(y),
|
|
776
776
|
() => {
|
|
777
777
|
r.value || $(e) && c();
|
|
@@ -780,20 +780,24 @@ function vn(e, t = {}) {
|
|
|
780
780
|
), {
|
|
781
781
|
validate: c,
|
|
782
782
|
reset: l,
|
|
783
|
-
isValid:
|
|
784
|
-
errors:
|
|
783
|
+
isValid: A(n),
|
|
784
|
+
errors: A(s)
|
|
785
785
|
};
|
|
786
786
|
}
|
|
787
|
-
const
|
|
788
|
-
x
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
if (
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
787
|
+
const x = Symbol("field-context"), Mn = (e) => {
|
|
788
|
+
j(x, e);
|
|
789
|
+
};
|
|
790
|
+
function Fn(e) {
|
|
791
|
+
if (e === void 0) {
|
|
792
|
+
const t = N(x);
|
|
793
|
+
if (!t) throw new Error("useFieldContext() must be called inside a Field component");
|
|
794
|
+
return t;
|
|
795
|
+
}
|
|
796
|
+
return N(x, e);
|
|
797
|
+
}
|
|
798
|
+
const xn = /* @__PURE__ */ W({
|
|
795
799
|
__name: "Field",
|
|
796
|
-
props: /* @__PURE__ */
|
|
800
|
+
props: /* @__PURE__ */ Z({
|
|
797
801
|
id: {},
|
|
798
802
|
name: {},
|
|
799
803
|
validation: { type: [String, Function, null] },
|
|
@@ -805,7 +809,7 @@ const X = Symbol("field-context"), Mn = (e) => {
|
|
|
805
809
|
}),
|
|
806
810
|
emits: ["update:modelValue"],
|
|
807
811
|
setup(e) {
|
|
808
|
-
const t = e, n =
|
|
812
|
+
const t = e, n = L(e, "modelValue"), r = oe(), s = ln(), o = G(), a = b({
|
|
809
813
|
get: () => s ? s.getFieldValue(t.name) : n.value,
|
|
810
814
|
set: (p) => {
|
|
811
815
|
s ? s.setFieldValue(t.name, p) : n.value = p;
|
|
@@ -817,32 +821,32 @@ const X = Symbol("field-context"), Mn = (e) => {
|
|
|
817
821
|
get: () => s ? s.getFields() : {},
|
|
818
822
|
set: () => {
|
|
819
823
|
}
|
|
820
|
-
}), c = vn(a, { rules: m, messages: i, fields: y }), l = h(!1), f = h(!1), u = h([]), g = b(() => a.value ?? null), d = b(() => c.isValid.value && u.value.length === 0), v = b(() => [...c.errors.value, ...u.value]), M = b(() => v.value[0] ?? null),
|
|
824
|
+
}), c = vn(a, { rules: m, messages: i, fields: y }), l = h(!1), f = h(!1), u = h([]), g = b(() => a.value ?? null), d = b(() => c.isValid.value && u.value.length === 0), v = b(() => [...c.errors.value, ...u.value]), M = b(() => v.value[0] ?? null), T = $(a), w = t.id ?? r, D = `${w}-error`, S = `${w}-help`, ee = (p) => {
|
|
821
825
|
u.value = Array.isArray(p) ? p : [p];
|
|
822
826
|
}, F = () => {
|
|
823
|
-
a.value =
|
|
827
|
+
a.value = T, l.value = !1, f.value = !1, u.value = [], c.reset();
|
|
824
828
|
};
|
|
825
|
-
|
|
829
|
+
k(
|
|
826
830
|
() => t.error,
|
|
827
831
|
(p) => {
|
|
828
832
|
p ? u.value = Array.isArray(p) ? p : [p] : u.value = [];
|
|
829
833
|
},
|
|
830
834
|
{ immediate: !0 }
|
|
831
835
|
);
|
|
832
|
-
const
|
|
833
|
-
id:
|
|
836
|
+
const V = b(() => ({
|
|
837
|
+
id: w,
|
|
834
838
|
name: t.name,
|
|
835
839
|
modelValue: a.value,
|
|
836
840
|
"aria-invalid": !!M.value,
|
|
837
841
|
"aria-describedby": M.value ? `${D} ${S}` : S,
|
|
838
842
|
"aria-errormessage": M.value ? D : void 0,
|
|
839
843
|
"onUpdate:modelValue": (p) => {
|
|
840
|
-
a.value = p, !f.value && p !==
|
|
844
|
+
a.value = p, !f.value && p !== T && (f.value = !0);
|
|
841
845
|
},
|
|
842
846
|
onBlur: () => {
|
|
843
847
|
l.value || (l.value = !0, c.validate());
|
|
844
848
|
}
|
|
845
|
-
})),
|
|
849
|
+
})), q = { for: w }, P = { id: D, role: "alert", "aria-live": "polite" }, C = { id: S };
|
|
846
850
|
return ae(() => {
|
|
847
851
|
s && s.addField(t.name, {
|
|
848
852
|
value: g,
|
|
@@ -859,10 +863,10 @@ const X = Symbol("field-context"), Mn = (e) => {
|
|
|
859
863
|
s && s.removeField(t.name);
|
|
860
864
|
}), Mn({
|
|
861
865
|
inputValue: a,
|
|
862
|
-
inputProps:
|
|
863
|
-
labelProps:
|
|
866
|
+
inputProps: V,
|
|
867
|
+
labelProps: q,
|
|
864
868
|
helpProps: C,
|
|
865
|
-
errorProps:
|
|
869
|
+
errorProps: P,
|
|
866
870
|
isValid: d,
|
|
867
871
|
isTouched: l,
|
|
868
872
|
isDirty: f,
|
|
@@ -870,13 +874,13 @@ const X = Symbol("field-context"), Mn = (e) => {
|
|
|
870
874
|
errors: v,
|
|
871
875
|
validate: c.validate,
|
|
872
876
|
reset: F
|
|
873
|
-
}), (p, Nn) => (
|
|
874
|
-
|
|
877
|
+
}), (p, Nn) => (_(), z("div", null, [
|
|
878
|
+
I(p.$slots, "default", U(K({
|
|
875
879
|
inputValue: a.value,
|
|
876
|
-
inputProps:
|
|
877
|
-
labelProps:
|
|
880
|
+
inputProps: V.value,
|
|
881
|
+
labelProps: q,
|
|
878
882
|
helpProps: C,
|
|
879
|
-
errorProps:
|
|
883
|
+
errorProps: P,
|
|
880
884
|
isValid: d.value,
|
|
881
885
|
isTouched: l.value,
|
|
882
886
|
isDirty: f.value,
|
|
@@ -889,7 +893,7 @@ const X = Symbol("field-context"), Mn = (e) => {
|
|
|
889
893
|
}
|
|
890
894
|
});
|
|
891
895
|
function jn() {
|
|
892
|
-
const e =
|
|
896
|
+
const e = G();
|
|
893
897
|
if (!e)
|
|
894
898
|
throw new Error(
|
|
895
899
|
"[Valiform] useLocale() must be used inside a component with FormsPlugin installed."
|
|
@@ -2,4 +2,40 @@ import type { InjectionKey } from 'vue';
|
|
|
2
2
|
import type { FieldContext } from '../types';
|
|
3
3
|
export declare const fieldContextKey: InjectionKey<FieldContext>;
|
|
4
4
|
export declare const useFieldContextProvider: (data: FieldContext) => void;
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Retrieves the `FieldContext` provided by the nearest `Field` component ancestor.
|
|
7
|
+
*
|
|
8
|
+
* **Three call signatures:**
|
|
9
|
+
*
|
|
10
|
+
* - `useFieldContext()` — no args. Returns `FieldContext` directly (no `!` needed).
|
|
11
|
+
* Throws at runtime if called outside a `Field`. Use this for components that
|
|
12
|
+
* must always be nested inside a `Field` (e.g. `FieldLabel`, `FieldError`).
|
|
13
|
+
*
|
|
14
|
+
* - `useFieldContext(fallback: FieldContext)` — with a fallback object. Returns
|
|
15
|
+
* `FieldContext` directly (no `!` needed). Use this for components that can work
|
|
16
|
+
* both inside and outside a `Field` (e.g. standalone inputs with `v-model`).
|
|
17
|
+
*
|
|
18
|
+
* - `useFieldContext(null)` — explicit null. Returns `FieldContext | null`.
|
|
19
|
+
* Use when you want to handle the absence of context manually.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* // Always inside a Field — throws at runtime if misused:
|
|
23
|
+
* const { labelProps } = useFieldContext();
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* // Standalone-capable input — works inside or outside a Field:
|
|
27
|
+
* const model = defineModel<string>({ default: '' });
|
|
28
|
+
* const { inputValue, inputProps } = useFieldContext({ inputValue: model });
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* // Manual null-handling:
|
|
32
|
+
* const ctx = useFieldContext(null);
|
|
33
|
+
* if (ctx) { ... }
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* // ❌ Wrong — `{}` does not satisfy FieldContext and will cause a type error:
|
|
37
|
+
* const { labelProps } = useFieldContext({});
|
|
38
|
+
*/
|
|
39
|
+
export declare function useFieldContext(): FieldContext;
|
|
40
|
+
export declare function useFieldContext(defaultData: null): FieldContext | null;
|
|
41
|
+
export declare function useFieldContext(defaultData: FieldContext): FieldContext;
|
package/dist/src/types.d.ts
CHANGED
|
@@ -33,7 +33,7 @@ export type InputProps = {
|
|
|
33
33
|
onBlur: () => void;
|
|
34
34
|
};
|
|
35
35
|
export interface FieldContext {
|
|
36
|
-
inputValue: WritableComputedRef<unknown>;
|
|
36
|
+
inputValue: WritableComputedRef<unknown> | Ref<unknown>;
|
|
37
37
|
inputProps: ComputedRef<InputProps>;
|
|
38
38
|
labelProps: {
|
|
39
39
|
for: string;
|