Skip to content

Form Methods

The form instance provides several methods for managing form state, validation, and data manipulation.

Form Instance

The form instance is created when you use v-model:form with the VsCompactForm component:

vue
<template>
  <VsCompactForm
    v-model:form="form"
    v-model:formValues="formValues"
    :schema="schema"
    @handle-submit="handleSubmit"
  />
</template>

<script setup>
  import { ref } from 'vue';

  const form = ref({});
  const formValues = ref({});
</script>

Available Methods

Validate

Validates all form fields according to their rules.

typescript
form.value.validate(); // Validates all fields

Behavior:

  • Checks all fields in the schema
  • Updates error state for invalid fields
  • Throws error if validation fails
  • Returns void

Example:

typescript
const handleSubmit = () => {
  try {
    form.value.validate();
    // Form is valid, proceed with submission
    console.log('Form is valid:', formValues.value);
  } catch (error) {
    // Form has validation errors
    console.error('Validation failed:', error.message);
  }
};

Reset

Clears all form values and validation errors.

typescript
form.value.reset(); // Clears form data and errors

Behavior:

  • Sets all form values to empty/initial state
  • Clears all validation errors
  • Resets form to initial state

Example:

typescript
const resetForm = () => {
  form.value.reset();
  console.log('Form reset to initial state');
};

Form Properties

Values

Access current form values.

typescript
const values = form.value.value; // Current form values

Type: Record<string, any>

Example:

typescript
const getFormData = () => {
  const currentValues = form.value.value;
  console.log('Current form values:', currentValues);
  return currentValues;
};

Errors

Access current validation errors.

typescript
const errors = form.value.errors; // Current validation errors

Type: IErrors (Record<string, string | boolean>)

Example:

typescript
const checkErrors = () => {
  const currentErrors = form.value.errors;
  const hasErrors = Object.keys(currentErrors).length > 0;

  if (hasErrors) {
    console.log('Form has errors:', currentErrors);
  } else {
    console.log('Form has no errors');
  }

  return hasErrors;
};

Form Interface

The complete form interface:

typescript
interface IForm {
  value: Record<string, any>; // Current form values
  errors: IErrors; // Current validation errors
  reset: () => void; // Reset form method
  validate: () => void; // Validate form method
}

Usage Examples

Complete Form Management

vue
<template>
  <VsCompactForm
    v-model:form="form"
    v-model:formValues="formValues"
    :schema="schema"
    @handle-submit="handleSubmit"
  />

  <div class="form-actions">
    <button @click="submitForm">Submit</button>
    <button @click="resetForm">Reset</button>
    <button @click="checkFormState">Check State</button>
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import VsCompactForm from '@/components/form/vs-compact-form.vue';

  const form = ref({});
  const formValues = ref({});

  const schema = [
    {
      name: 'name',
      type: 'text',
      label: 'Name',
      rules: ['required'],
    },
    {
      name: 'email',
      type: 'text',
      label: 'Email',
      rules: ['required', 'email'],
    },
  ];

  const submitForm = () => {
    try {
      form.value.validate();
      console.log('Form submitted successfully:', form.value.value);
      // Proceed with API call or other logic
    } catch (error) {
      console.error('Form validation failed:', error.message);
    }
  };

  const resetForm = () => {
    form.value.reset();
    console.log('Form has been reset');
  };

  const checkFormState = () => {
    const values = form.value.value;
    const errors = form.value.errors;

    console.log('Form values:', values);
    console.log('Form errors:', errors);
    console.log('Has errors:', Object.keys(errors).length > 0);
  };
</script>

Conditional Validation

typescript
const validateSpecificField = (fieldName: string) => {
  // This would need to be implemented in the form system
  // For now, validate all fields
  form.value.validate();
};

const isFieldValid = (fieldName: string) => {
  const errors = form.value.errors;
  return !errors[fieldName];
};

Form State Management

typescript
const getFormState = () => {
  return {
    values: form.value.value,
    errors: form.value.errors,
    isValid: Object.keys(form.value.errors).length === 0,
    hasChanges: Object.keys(form.value.value).length > 0,
  };
};

const saveFormState = () => {
  const state = getFormState();
  localStorage.setItem('formState', JSON.stringify(state));
};

const loadFormState = () => {
  const saved = localStorage.getItem('formState');
  if (saved) {
    const state = JSON.parse(saved);
    formValues.value = state.values;
  }
};

Error Handling

Validation Errors

When validation fails, the form throws an error:

typescript
try {
  form.value.validate();
} catch (error) {
  if (error.message === 'Помилка валідації') {
    // Handle validation errors
    console.log('Validation errors:', form.value.errors);
  }
}

Error States

Check for specific error conditions:

typescript
const hasRequiredErrors = () => {
  const errors = form.value.errors;
  return Object.values(errors).some(error => error === "Це поле є обов'язковим");
};

const hasEmailErrors = () => {
  const errors = form.value.errors;
  return Object.values(errors).some(error => error === 'Неправильний email');
};

Best Practices

  1. Always validate before submission to ensure data integrity
  2. Handle validation errors gracefully with user-friendly messages
  3. Reset forms when appropriate to provide good UX
  4. Monitor form state for debugging and user feedback
  5. Use try-catch blocks when calling validate()
  6. Check error states before proceeding with form actions
  7. Save form state for complex forms that users might want to resume