This commit is contained in:
2026-03-19 19:29:30 +03:00
parent ecb3bd7714
commit 69afca68cf
4 changed files with 1116 additions and 353 deletions

View File

@@ -6,12 +6,11 @@
<title>Регистрация | Rabota.Today</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* Мобильные стили */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}
body {
@@ -123,6 +122,12 @@
font-size: 14px;
}
.required-star {
color: #ef4444;
margin-left: 4px;
font-size: 14px;
}
.input-group input {
width: 100%;
padding: 14px 16px;
@@ -142,6 +147,11 @@
box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
}
.input-group input.error {
border-color: #ef4444;
background: #fef2f2;
}
.input-row {
display: flex;
gap: 10px;
@@ -219,7 +229,61 @@
font-size: 13px;
}
/* Адаптация для очень маленьких экранов */
.password-requirements {
background: #f0f7ff;
border-radius: 20px;
padding: 12px 16px;
margin: 15px 0;
font-size: 12px;
}
.password-requirements p {
color: #1f3f60;
font-weight: 600;
margin-bottom: 8px;
display: flex;
align-items: center;
gap: 5px;
}
.requirement {
color: #4f7092;
margin: 4px 0;
display: flex;
align-items: center;
gap: 5px;
}
.requirement.valid {
color: #10b981;
}
.requirement.valid i {
color: #10b981;
}
.requirement.invalid {
color: #ef4444;
}
.requirement.invalid i {
color: #ef4444;
}
.footer {
text-align: center;
padding: 20px 30px;
background: #f8fafc;
border-top: 1px solid #dee9f5;
font-size: 13px;
color: #4f7092;
}
.footer a {
color: #3b82f6;
text-decoration: none;
}
@media (max-width: 380px) {
.input-row {
flex-direction: column;
@@ -237,7 +301,7 @@
<div class="register-header">
<h1>
<i class="fas fa-briefcase"></i>
МП.Ярмарка
Rabota.Today
</h1>
<p>Регистрация на ярмарке вакансий</p>
</div>
@@ -264,36 +328,65 @@
<form id="registerForm" onsubmit="handleRegister(event)">
<div class="input-group">
<label><i class="fas fa-user-circle"></i> ФИО *</label>
<input type="text" id="fullName" placeholder="Иванов Иван" required>
<label>
<i class="fas fa-user-circle"></i>
ФИО <span class="required-star">*</span>
</label>
<input type="text" id="fullName" placeholder="Иванов Иван Иванович" required>
</div>
<div class="input-group">
<label><i class="fas fa-envelope"></i> Email *</label>
<label>
<i class="fas fa-envelope"></i>
Email <span class="required-star">*</span>
</label>
<input type="email" id="email" placeholder="ivan@example.com" required>
</div>
<div class="input-row">
<div class="input-group">
<label><i class="fas fa-phone-alt"></i> Телефон *</label>
<label>
<i class="fas fa-phone-alt"></i>
Телефон <span class="required-star">*</span>
</label>
<input type="tel" id="phone" placeholder="+7 (999) 123-45-67" required>
</div>
<div class="input-group">
<label><i class="fab fa-telegram-plane"></i> Telegram</label>
<input type="text" id="telegram" placeholder="@username">
<label>
<i class="fab fa-telegram-plane"></i>
Telegram <span class="required-star">*</span>
</label>
<input type="text" id="telegram" placeholder="@username" required>
</div>
</div>
<div class="input-group">
<label><i class="fas fa-lock"></i> Пароль *</label>
<label>
<i class="fas fa-lock"></i>
Пароль <span class="required-star">*</span>
</label>
<input type="password" id="password" placeholder="Минимум 6 символов" required>
</div>
<div class="input-group">
<label><i class="fas fa-lock"></i> Подтверждение *</label>
<label>
<i class="fas fa-lock"></i>
Подтверждение <span class="required-star">*</span>
</label>
<input type="password" id="confirmPassword" placeholder="Повторите пароль" required>
</div>
<!-- Требования к паролю -->
<div class="password-requirements" id="passwordRequirements">
<p><i class="fas fa-shield-alt"></i> Требования к паролю:</p>
<div class="requirement" id="reqLength">
<i class="far fa-circle"></i> Минимум 6 символов
</div>
<div class="requirement" id="reqMatch">
<i class="far fa-circle"></i> Пароли совпадают
</div>
</div>
<button type="submit" class="btn-register" id="registerBtn">
<span>Зарегистрироваться</span>
<i class="fas fa-arrow-right"></i>
@@ -305,17 +398,17 @@
<a href="/login">Войти</a>
</div>
</div>
<div class="footer">
© 2024 Rabota.Today - Ярмарка вакансий.
<a href="/">На главную</a>
</div>
</div>
<script>
const currentProtocol = window.location.protocol; // http: или https:
const currentHost = window.location.host; // yarmarka.rabota.today или IP:порт
let API_BASE_URL = `${currentProtocol}//${currentHost}/api`;
const API_BASE_URL = window.location.protocol + '//' + window.location.host + '/api';
let isSubmitting = false;
// Определение мобильного устройства
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
// Переключение роли
document.getElementById('roleEmployeeBtn').addEventListener('click', () => {
document.getElementById('roleEmployeeBtn').classList.add('active');
@@ -327,6 +420,69 @@
document.getElementById('roleEmployeeBtn').classList.remove('active');
});
// Валидация пароля в реальном времени
const passwordInput = document.getElementById('password');
const confirmInput = document.getElementById('confirmPassword');
function validatePassword() {
const password = passwordInput.value;
const confirm = confirmInput.value;
const reqLength = document.getElementById('reqLength');
const reqMatch = document.getElementById('reqMatch');
// Проверка длины
if (password.length >= 6) {
reqLength.className = 'requirement valid';
reqLength.innerHTML = '<i class="fas fa-check-circle"></i> Минимум 6 символов ✓';
} else {
reqLength.className = 'requirement invalid';
reqLength.innerHTML = '<i class="fas fa-times-circle"></i> Минимум 6 символов';
}
// Проверка совпадения
if (password && confirm && password === confirm) {
reqMatch.className = 'requirement valid';
reqMatch.innerHTML = '<i class="fas fa-check-circle"></i> Пароли совпадают ✓';
} else if (confirm) {
reqMatch.className = 'requirement invalid';
reqMatch.innerHTML = '<i class="fas fa-times-circle"></i> Пароли совпадают';
} else {
reqMatch.className = 'requirement';
reqMatch.innerHTML = '<i class="far fa-circle"></i> Пароли совпадают';
}
}
passwordInput.addEventListener('input', validatePassword);
confirmInput.addEventListener('input', validatePassword);
// Функция для проверки корректности Telegram username
function validateTelegram(telegram) {
if (!telegram) return false;
// Telegram username может начинаться с @ или без него
// Допустимые символы: буквы, цифры, подчеркивание
const cleanTelegram = telegram.replace('@', '');
return /^[a-zA-Z0-9_]{5,32}$/.test(cleanTelegram);
}
// Функция для форматирования телефона
function formatPhone(phone) {
// Удаляем все нецифровые символы
let digits = phone.replace(/\D/g, '');
// Если номер начинается с 8 или 7, нормализуем
if (digits.length === 11) {
if (digits.startsWith('8')) {
digits = '7' + digits.substring(1);
}
} else if (digits.length === 10) {
digits = '7' + digits;
}
return digits;
}
// Показать сообщение об ошибке
function showError(message) {
const errorDiv = document.getElementById('errorMessage');
const errorText = document.getElementById('errorText');
@@ -335,112 +491,172 @@
setTimeout(() => {
errorDiv.style.display = 'none';
}, 4000);
}, 5000);
}
// Показать сообщение об успехе
function showSuccess(message) {
const successDiv = document.getElementById('successMessage');
const successText = document.getElementById('successText');
successText.textContent = message;
successDiv.style.display = 'flex';
setTimeout(() => {
successDiv.style.display = 'none';
}, 3000);
}
// Показать состояние загрузки
function setLoading(isLoading) {
const btn = document.getElementById('registerBtn');
const registerBtn = document.getElementById('registerBtn');
if (isLoading) {
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Регистрация...';
btn.disabled = true;
registerBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Регистрация...';
registerBtn.disabled = true;
isSubmitting = true;
} else {
btn.innerHTML = '<span>Зарегистрироваться</span><i class="fas fa-arrow-right"></i>';
btn.disabled = false;
registerBtn.innerHTML = '<span>Зарегистрироваться</span><i class="fas fa-arrow-right"></i>';
registerBtn.disabled = false;
isSubmitting = false;
}
}
// Обработка регистрации
async function handleRegister(event) {
event.preventDefault();
if (isSubmitting) return;
// Получаем значения полей
const fullName = document.getElementById('fullName').value.trim();
const email = document.getElementById('email').value.trim();
const phone = document.getElementById('phone').value.trim();
const telegram = document.getElementById('telegram').value.trim() || null;
const telegram = document.getElementById('telegram').value.trim();
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;
// Определяем роль
const role = document.getElementById('roleEmployeeBtn').classList.contains('active') ? 'employee' : 'employer';
// Валидация
if (!fullName || !email || !phone || !password) {
showError('Заполните все обязательные поля');
// Валидация ФИО
if (!fullName) {
showError('Введите ФИО');
document.getElementById('fullName').focus();
return;
}
// Валидация email
if (!email) {
showError('Введите email');
document.getElementById('email').focus();
return;
}
if (!email.includes('@') || !email.includes('.')) {
showError('Введите корректный email');
document.getElementById('email').focus();
return;
}
// Валидация телефона
if (!phone) {
showError('Введите номер телефона');
document.getElementById('phone').focus();
return;
}
const phoneDigits = formatPhone(phone);
if (phoneDigits.length !== 11) {
showError('Введите корректный номер телефона (10 или 11 цифр)');
document.getElementById('phone').focus();
return;
}
// Валидация Telegram
if (!telegram) {
showError('Введите Telegram username');
document.getElementById('telegram').focus();
return;
}
if (!validateTelegram(telegram)) {
showError('Telegram username должен содержать от 5 до 32 символов (буквы, цифры, _)');
document.getElementById('telegram').focus();
return;
}
// Валидация пароля
if (password.length < 6) {
showError('Пароль должен быть минимум 6 символов');
showError('Пароль должен содержать минимум 6 символов');
document.getElementById('password').focus();
return;
}
if (password !== confirmPassword) {
showError('Пароли не совпадают');
document.getElementById('confirmPassword').focus();
return;
}
// Форматируем телефон для отправки
const formattedPhone = '+' + phoneDigits;
// Форматируем Telegram (добавляем @ если нет)
let formattedTelegram = telegram;
if (!telegram.startsWith('@')) {
formattedTelegram = '@' + telegram;
}
// Подготавливаем данные для отправки
const userData = {
full_name: fullName,
email: email,
phone: formattedPhone,
telegram: formattedTelegram,
password: password,
role: role
};
console.log('📤 Отправка данных регистрации:', {
...userData,
password: '***скрыто***'
});
setLoading(true);
try {
const userData = {
full_name: fullName,
email: email,
phone: phone,
telegram: telegram,
password: password,
role: role
};
console.log('Sending registration request...', { email: userData.email });
const response = await fetch(`${API_BASE_URL}/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
'Accept': 'application/json'
},
body: JSON.stringify(userData),
credentials: 'include' // Важно для мобильных
body: JSON.stringify(userData)
});
console.log('Response status:', response.status);
const data = await response.json();
console.log('📥 Ответ сервера:', data);
if (!response.ok) {
throw new Error(data.detail || 'Ошибка регистрации');
}
console.log('Registration successful');
// Успешная регистрация
showSuccess('Регистрация успешна! Перенаправляем...');
// Сохраняем токен
if (data.access_token) {
localStorage.setItem('accessToken', data.access_token);
localStorage.setItem('userId', data.user_id);
localStorage.setItem('userRole', data.role);
localStorage.setItem('userName', data.full_name);
localStorage.setItem('accessToken', data.access_token);
localStorage.setItem('userId', data.user_id);
localStorage.setItem('userRole', data.role);
localStorage.setItem('userName', data.full_name);
showSuccess('Регистрация успешна! Перенаправляем...');
setTimeout(() => {
window.location.href = '/profile';
}, 1500);
} else {
throw new Error('Токен не получен');
}
// Перенаправляем в профиль через секунду
setTimeout(() => {
window.location.href = '/profile';
}, 1500);
} catch (error) {
console.error('Registration error:', error);
showError(error.message || 'Ошибка соединения');
console.error('❌ Ошибка регистрации:', error);
showError(error.message);
setLoading(false);
}
}
@@ -454,6 +670,25 @@
}
});
// Автоматическое добавление @ в Telegram
document.getElementById('telegram').addEventListener('blur', function(e) {
let value = e.target.value.trim();
if (value && !value.startsWith('@')) {
e.target.value = '@' + value.replace(/[^a-zA-Z0-9_]/g, '');
}
});
// Ограничение ввода для Telegram (только буквы, цифры, _)
document.getElementById('telegram').addEventListener('input', function(e) {
let value = e.target.value;
// Если начинается с @, разрешаем @ только в начале
if (value.startsWith('@')) {
e.target.value = '@' + value.substring(1).replace(/[^a-zA-Z0-9_]/g, '');
} else {
e.target.value = value.replace(/[^a-zA-Z0-9_]/g, '');
}
});
// Проверка существующей сессии
if (localStorage.getItem('accessToken')) {
window.location.href = '/profile';