|
| 1 | +import { MAX_HASHTAG_COUNT, MAX_COMMENT_LENGTH } from './const.js'; |
| 2 | +import { getTags, isValidTag, isValidCount, hasUniqueTags } from './utils.js'; |
| 3 | + |
| 4 | +const form = document.querySelector('.img-upload__form'); |
| 5 | +const hashtagField = form.querySelector('.text__hashtags'); |
| 6 | +const commentField = form.querySelector('.text__description'); |
| 7 | + |
| 8 | +const ERROR_MESSAGES = { |
| 9 | + hashtags: { |
| 10 | + count: () => 'превышено количество хэштегов', |
| 11 | + unique: () => 'хэштеги повторяются', |
| 12 | + format: () => 'введён невалидный хэштег', |
| 13 | + }, |
| 14 | + comment: { |
| 15 | + length: (max) => `длина комментария больше ${max} символов`, |
| 16 | + }, |
| 17 | +}; |
| 18 | + |
| 19 | +const formConfig = { |
| 20 | + classTo: 'img-upload__field-wrapper', |
| 21 | + errorTextParent: 'img-upload__field-wrapper', |
| 22 | + errorTextClass: 'img-upload__field-wrapper--error', |
| 23 | +}; |
| 24 | + |
| 25 | +const pristine = new Pristine(form, formConfig); |
| 26 | + |
| 27 | +const initValidation = () => { |
| 28 | + [hashtagField, commentField].forEach((field) => { |
| 29 | + field.addEventListener('keydown', (evt) => { |
| 30 | + if (evt.key === 'Escape') { |
| 31 | + evt.stopPropagation(); |
| 32 | + } |
| 33 | + }); |
| 34 | + }); |
| 35 | + |
| 36 | + pristine.addValidator( |
| 37 | + hashtagField, |
| 38 | + (value) => isValidCount(getTags(value), MAX_HASHTAG_COUNT), |
| 39 | + ERROR_MESSAGES.hashtags.count() |
| 40 | + ); |
| 41 | + |
| 42 | + pristine.addValidator( |
| 43 | + hashtagField, |
| 44 | + (value) => hasUniqueTags(getTags(value)), |
| 45 | + ERROR_MESSAGES.hashtags.unique() |
| 46 | + ); |
| 47 | + |
| 48 | + pristine.addValidator( |
| 49 | + hashtagField, |
| 50 | + (value) => getTags(value).every(isValidTag), |
| 51 | + ERROR_MESSAGES.hashtags.format() |
| 52 | + ); |
| 53 | + |
| 54 | + pristine.addValidator( |
| 55 | + commentField, |
| 56 | + (value) => value.length <= MAX_COMMENT_LENGTH, |
| 57 | + ERROR_MESSAGES.comment.length(MAX_COMMENT_LENGTH) |
| 58 | + ); |
| 59 | +}; |
| 60 | + |
| 61 | +const isValid = () => pristine.validate(); |
| 62 | + |
| 63 | +const resetValidation = () => pristine.reset(); |
| 64 | + |
| 65 | +export { initValidation, isValid, resetValidation }; |
0 commit comments