Skip to content

Commit

Permalink
clear application.js
Browse files Browse the repository at this point in the history
  • Loading branch information
sseezov committed Mar 27, 2024
1 parent 1817aac commit 6d8eb2e
Showing 1 changed file with 0 additions and 78 deletions.
78 changes: 0 additions & 78 deletions src/application.js
Original file line number Diff line number Diff line change
@@ -1,78 +0,0 @@
import _ from 'lodash';
import onChange from 'on-change';
import axios from 'axios';

export const validateName = (name) => (name.trim().length ? [] : ['name cannot be empty']);
export const validateEmail = (email) => (/\w+@\w+/.test(email) ? [] : ['invalid email']);
const validateField = (fieldname, data) => (fieldname === 'name' ? validateName(data) : validateEmail(data));

export default () => {
const formHTML = `
<form id="registrationForm">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Введите ваше имя" name="name" required>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="text" class="form-control" id="inputEmail" placeholder="Введите email"
name="email" required>
</div>
<input type="submit" value="Submit" class="btn btn-primary" disabled>
</form>`;

const formContainer = document.querySelector('.form-container');
formContainer.innerHTML = formHTML;

const state = {
errors: {
name: [],
email: [],
},
values: {
name: '',
email: '',
},
};

const form = document.querySelector('form');
const submit = document.querySelector('[type="submit"]');

const hasErrors = () => (_.values(state.errors).reduce((acc, curr) => (curr.length > 0
? acc.concat(curr)
: acc), [])
.length > 0);

const watchedState = onChange(state, (path) => {
const selector = path.split('.')[1];
const input = document.querySelector(`[name=${selector}]`);
const isFieldValid = validateField(selector, state.values[selector]).length === 0;
if (!isFieldValid) {
input.classList.remove('is-valid');
input.classList.add('is-invalid');
} else {
input.classList.remove('is-invalid');
input.classList.add('is-valid');
}
submit.disabled = hasErrors(state);
});

form.addEventListener('input', (e) => {
e.preventDefault();
const targetName = e.target.name;
const targetData = new FormData(form).get(targetName);
watchedState.values[targetName] = targetData;
watchedState.errors[targetName] = (validateField(targetName, targetData));
});

form.addEventListener('submit', (e) => {
e.preventDefault();
axios.post('/users', state.values)
.then((response) => {
document.body.innerHTML = `<p>${response.data.message}</p>`;
})
.catch((error) => {
console.log(error);
});
});
};

0 comments on commit 6d8eb2e

Please sign in to comment.