Skip to content

Commit

Permalink
feat: added useIsTouched helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Dec 18, 2020
1 parent 6b7e4ab commit fdb2d5a
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/vee-validate/src/index.ts
Expand Up @@ -10,3 +10,4 @@ export { ValidationResult, FormActions, FormState, FormValidationResult, FormCon
export * from './useErrors';
export { useResetForm } from './useResetForm';
export * from './useIsDirty';
export * from './useIsTouched';
25 changes: 25 additions & 0 deletions packages/vee-validate/src/useIsTouched.ts
@@ -0,0 +1,25 @@
import { computed } from 'vue';
import { FormSymbol } from './symbols';
import { injectWithSelf } from './utils';

/**
* If a field is touched or not
*/
export function useIsFieldTouched(path: string) {
const form = injectWithSelf(FormSymbol);

return computed(() => {
return form?.fields.value[path]?.meta.touched;
});
}

/**
* If the form is touched or not
*/
export function useIsFormTouched() {
const form = injectWithSelf(FormSymbol);

return computed(() => {
return form?.meta.value.touched;
});
}
63 changes: 63 additions & 0 deletions packages/vee-validate/tests/useIsTouched.spec.ts
@@ -0,0 +1,63 @@
import flushPromises from 'flush-promises';
import { useField, useForm, useIsFormTouched, useIsFieldTouched } from '@/vee-validate';
import { dispatchEvent, mountWithHoc } from './helpers';

describe('useIsTouched()', () => {
test('gives access to a field isTouched status', async () => {
mountWithHoc({
setup() {
useForm();
const { value, handleBlur } = useField('test');
const isTouched = useIsFieldTouched('test');

return {
value,
isTouched,
handleBlur,
};
},
template: `
<input name="field" v-model="value" @blur="handleBlur" />
<span>{{ isTouched.toString() }}</span>
`,
});
await flushPromises();

const input = document.querySelector('input');
const error = document.querySelector('span');
expect(error?.textContent).toBe('false');

dispatchEvent(input as any, 'blur');

await flushPromises();
expect(error?.textContent).toBe('true');
});

test('gives access to the forms isTouched status', async () => {
mountWithHoc({
setup() {
useForm();
const { value, handleBlur } = useField('test');
const isTouched = useIsFormTouched();

return {
value,
isTouched,
handleBlur,
};
},
template: `
<input name="field" v-model="value" @blur="handleBlur" />
<span>{{ isTouched.toString() }}</span>
`,
});

const input = document.querySelector('input');
const error = document.querySelector('span');
expect(error?.textContent).toBe('false');

dispatchEvent(input as any, 'blur');
await flushPromises();
expect(error?.textContent).toBe('true');
});
});

0 comments on commit fdb2d5a

Please sign in to comment.