summaryrefslogtreecommitdiff
path: root/src/lib/form_utils.ts
blob: 43fe0faed59087e831a1b7f33811f207b7dd8b77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import FieldProperties from "../components/forms/fields/field_properties";
import Token from "./token";

export interface FormError {
  field_name: string;
  message: string;
}

export function deleteEmptyFields(form: FormData) {
  const trimmed_form = new FormData();

  for(const key of form.keys()) {
    if(form.get(key) != '')
      trimmed_form.append(key, form.get(key));
  }

  return trimmed_form;
}

export function setFormErrorsInSessionStorage(errors: Array<any>) {
    for(const [key, value] of Object.entries(errors)) {
      sessionStorage.setItem(key, value);
    }
}

export function setFieldErrorMessages(fields: FieldProperties[], errors: FormError[]) {
  for(const field of fields) {
    const error = errors.find(e => e.field_name == field.name)
    if(error){
      field.error_message = error.message;
    }
  }

  return fields;
}

export function clearSessionStorage() {
  const token = new Token();
  const stored_token = sessionStorage.getItem('token');
  const refresh_token = sessionStorage.getItem('refresh');

  sessionStorage.clear();

  if(stored_token && refresh_token) {
    token.set(stored_token);
    token.setRefresh(refresh_token);
  }
}

export function formHasErrors(fields: Array<string>) {
  for(const field_key of fields) {
    if(sessionStorage.getItem(field_key))
      return true;
  }

  return false;
}

export function renderErrors(errors: Array<Error>) {
  for(const error of errors) {
    const field_div = document.getElementById(error.field_div_id);
    const input_label = field_div?.querySelector("label");
    const input_field = field_div?.querySelector("input");
    input_label?.classList.add("text-red-700");
    input_field?.classList.add("bg-red-50 border border-red-500 text-red-900 placeholder-red-700 focus:ring-red-500 dark:bg-gray-700 focus:border-red-500");
  }
}