-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathform.validation.helper.js
More file actions
60 lines (48 loc) · 1.93 KB
/
form.validation.helper.js
File metadata and controls
60 lines (48 loc) · 1.93 KB
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
import { getTranslator } from './context.helper';
import { getIconPath } from './icon.helper';
const formatErrorLine = (errorMessage) => {
const errorIcon = `<svg class="ibexa-icon ibexa-icon--small-medium ibexa-form-error__icon">
<use xlink:href="${getIconPath('notice')}"></use>
</svg>`;
const container = document.createElement('em');
const errorMessageNode = document.createTextNode(errorMessage);
container.classList.add('ibexa-form-error__row');
container.insertAdjacentHTML('beforeend', errorIcon);
container.append(errorMessageNode);
return container;
};
const checkIsEmpty = (field) => {
let errorMessage = '';
const Translator = getTranslator();
const input = field.querySelector('.ibexa-input');
const label = field.querySelector('.ids-label');
if (label) {
const fieldName = label.innerText;
errorMessage = Translator.trans(/* @Desc("%fieldName% cannot be empty.") */ 'error.required.field', { fieldName }, 'forms');
} else {
errorMessage = Translator.trans(/* @Desc("This value should not be blank.") */ 'error.required.field_not_blank', {}, 'forms');
}
return {
isValid: (input.value || input.value === 0) ?? false,
errorMessage,
};
};
const validateIsEmptyField = (field) => {
const input = field.querySelector('.ibexa-input');
const label = field.querySelector('.ids-label');
const errorWrapper = field.querySelector('.ibexa-form-error');
const validatorOutput = checkIsEmpty(field);
const { isValid, errorMessage } = validatorOutput;
if (input) {
input.classList.toggle('is-invalid', !isValid);
}
if (label && input) {
label.classList.toggle('is-invalid', !isValid);
}
errorWrapper.innerText = '';
if (!isValid) {
errorWrapper.append(formatErrorLine(errorMessage));
}
return validatorOutput;
};
export { formatErrorLine, validateIsEmptyField, checkIsEmpty };