Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Правда или действие #9

Merged
3 changes: 2 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ <h2 class="pictures__title visually-hidden">Фотографии других
<section class="img-upload">
<div class="img-upload__wrapper">
<h2 class="img-upload__title visually-hidden">Загрузка фотографии</h2>
<form class="img-upload__form" id="upload-select-image" autocomplete="off">
<form class="img-upload__form" id="upload-select-image" method="post" action="https://31.javascript.htmlacademy.pro/kekstagram" enctype="multipart/form-data" autocomplete="off">

<!-- Изначальное состояние поля для загрузки изображения -->
<fieldset class="img-upload__start">
Expand Down Expand Up @@ -233,6 +233,7 @@ <h2 class="success__title">Изображение успешно загруже
<h2 class="data-error__title">Не удалось загрузить данные</h2>
</section>
</template>
<script src="vendor/pristine/pristine.min.js" type="text/javascript"></script>
<script src="js/main.js" type="module"></script>
<script src="js/functions.js"></script>
</body>
Expand Down
1 change: 1 addition & 0 deletions js/main.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { listPhotos } from './create-photos.js';
import {renderThumbnails} from './render-photos.js';
import './open-full-photo.js';
import './validate-form.js';

renderThumbnails(listPhotos);

43 changes: 43 additions & 0 deletions js/open-form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { body } from './open-full-photo.js';
import { isEscapeKey } from './utils.js';
import './validate-form.js';

const imgUploadForm = document.querySelector('.img-upload__form');
const imgUploadInput = imgUploadForm.querySelector('.img-upload__input');
const imgUploadOverlay = imgUploadForm.querySelector('.img-upload__overlay');
const imgUploadClose = imgUploadForm.querySelector('.img-upload__cancel');
const imgHashtags = imgUploadForm.querySelector('.text__hashtags');
const imgDescription = imgUploadForm.querySelector('.text__description');


const onDocumentKeydown = (evt) => {
if (isEscapeKey(evt) && document.activeElement !== imgHashtags && document.activeElement !== imgDescription) {
evt.preventDefault();
closeUploadForm();
}
};

const clearForm = () => {
imgUploadInput.value = '';
imgHashtags.value = '';
imgDescription.value = '';
};

function openUploadForm() {
imgUploadOverlay.classList.remove('hidden');
body.classList.add('modal-open');
document.addEventListener('keydown', onDocumentKeydown);
imgUploadClose.addEventListener('click', closeUploadForm);
}

function closeUploadForm() {
imgUploadOverlay.classList.add('hidden');
body.classList.remove('modal-open');
document.removeEventListener('keydown', onDocumentKeydown);
imgUploadClose.removeEventListener('click', closeUploadForm);
clearForm();
}

imgUploadInput.addEventListener('change', openUploadForm);

export { imgUploadForm, imgHashtags };
1 change: 1 addition & 0 deletions js/open-full-photo.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ picturesContainer.addEventListener('click', (evt) => {

bigPictureClose.addEventListener('click', closeFullPhoto);

export { body };
85 changes: 85 additions & 0 deletions js/validate-form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { imgUploadForm, imgHashtags } from './open-form.js';

const imgComments = imgUploadForm.querySelector('.text__description');
const MAX_COMMENT_LENGTH = 140;
const MAX_HASH_LENGTH = 20;
const MAX_NUMBER_HASHES = 5;
let hashArray = [];
const hashErrorMassege = [];

const checkHashErrors = () => [
{
check: hashArray.some((hash) => hash.slice(1).includes('#')),
error: ' хэштеги разделяются пробелами',
},
{
check: hashArray.some((hash) => hash[0] !== '#'),
error: ' хэштег начинается с символа # (решётка)',
},
{
check: hashArray.some((hash) => hash === '#'),
error: ' хеш-тег не может состоять только из одной решётки',
},
{
check: hashArray.some(
(hash) => !/^[a-zа-яё0-9]{1,19}$/i.test(hash.slice(1))
),
error: ' строка после решётки должна состоять из букв и чисел',
},
{
check: hashArray.some((hash) => hash.length > MAX_HASH_LENGTH),
error: ` максимальная длина одного хэштега ${MAX_HASH_LENGTH} символов, включая решётку`,
},
{
check: hashArray.length > MAX_NUMBER_HASHES,
error: ` нельзя указать больше ${MAX_NUMBER_HASHES} хэштегов`,
},
{
check: [...new Set(hashArray)].length !== hashArray.length,
error: ' один и тот же хэштег не может быть использован дважды',
},
];

const pristine = new Pristine(
imgUploadForm,
{
classTo: 'img-upload__field-wrapper',
errorClass: 'img-upload__field-wrapper--error',
errorTextParent: 'img-upload__field-wrapper',
},
false
);

function validateHashtags(value) {
if (!value) {
return true;
}
hashArray = value.trim().toLowerCase().split(' ');

checkHashErrors().map((errorHash) => {
if (errorHash.check) {
hashErrorMassege.push(errorHash.error);
}
return hashErrorMassege;
});
return hashErrorMassege.length === 0;
}

function validateComment(value) {
return value.length >= 0 && value.length < 140;
}

const commentErrorMassege = () =>
`максимальная длина комментария ${MAX_COMMENT_LENGTH}`;

const hashesErrorText = () => hashErrorMassege;

pristine.addValidator(imgHashtags, validateHashtags,hashesErrorText);
pristine.addValidator(imgComments, validateComment, commentErrorMassege);

imgUploadForm.addEventListener('submit', (evt) => {
evt.preventDefault();
if (pristine.validate()) {
imgUploadForm.submit();
}
});
Loading