aboutsummaryrefslogtreecommitdiffstats
path: root/src/helpers/validation-helpers.js
blob: a8a242d54533663c5e8917b20d51116058bb3738 (plain) (blame)
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
export function required({ field }) {
  const isValid = (field.value.trim() !== '');
  return [isValid, `${field.label} is required`];
}

export function email({ field }) {
  const value = field.value.trim();
  let isValid = false;

  if (value !== '') {
    isValid = Boolean(value.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}/i));
  } else {
    isValid = true;
  }

  return [isValid, `${field.label} not valid`];
}

export function url({ field }) {
  const value = field.value.trim();
  let isValid = false;

  if (value !== '') {
    // eslint-disable-next-line
    isValid = Boolean(value.match(/(^|[\s.:;?\-\]<(])(https?:\/\/[-\w;/?:@&=+$|_.!~*|'()[\]%#,☺]+[\w/#](\(\))?)(?=$|[\s',|().:;?\-[\]>)])/i));
  } else {
    isValid = true;
  }

  return [isValid, `${field.label} is not a valid url`];
}

export function minLength(length) {
  return ({ field }) => {
    let isValid = true;
    if (field.touched) {
      isValid = field.value.length >= length;
    }
    return [isValid, `${field.label} should be at least ${length} characters long.`];
  };
}

export function oneRequired(targets) {
  return ({ field, form }) => {
    const invalidFields = targets.filter(target => form.$(target).value === '');
    return [targets.length !== invalidFields.length, `${field.label} is required`];
  };
}