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

Sign Up Validate #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/controller/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,15 @@ import {
getSectionsWithLessons,
countEnrolledUsersInCourse,
} from "../service/course.service";
const { validationResult } = require('express-validator');

export const register = asyncHandler(async (req: Request, res: Response) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(400).json({ status: 400, errors: errors.array() });
return;
}

const {
name,
email,
Expand Down
51 changes: 51 additions & 0 deletions src/entity/dto/register.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const { body, validationResult } = require('express-validator');
exports.registerValidation = [
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ủa htrc c suggest là dùng class-validator mà ta ơi

body('name')
.notEmpty().withMessage('Tên người dùng là bắt buộc.')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • I18n message
  • 3, 50, ... -> các giá trị hằng số khai báo trong file constant nhé

.isLength({ min: 3, max: 50 }).withMessage('Tên người dùng phải có từ 3 đến 50 ký tự.'),

body('email')
.isEmail().withMessage('Email không hợp lệ.')
.notEmpty().withMessage('Email là bắt buộc.'),

body('phone_number')
.notEmpty().withMessage('Số điện thoại là bắt buộc.')
.matches(/^\d{10,15}$/).withMessage('Số điện thoại không hợp lệ.'),

body('date_of_birth')
.notEmpty().withMessage('Ngày sinh là bắt buộc.')
.isDate().withMessage('Ngày sinh không hợp lệ.'),

body('gender')
.notEmpty().withMessage('Giới tính là bắt buộc.')
.isIn(['male', 'female', 'other']).withMessage('Giới tính không hợp lệ.'),

body('address')
.notEmpty().withMessage('Địa chỉ là bắt buộc.')
.isLength({ max: 100 }).withMessage('Địa chỉ không được vượt quá 100 ký tự.'),

body('role')
.notEmpty().withMessage('Vai trò là bắt buộc.')
.isIn(['user', 'professor']).withMessage('Vai trò không hợp lệ.'),

body('department')
.if(body('role').equals('professor'))
.notEmpty().withMessage('Bộ phận là bắt buộc cho vai trò giáo sư.')
.isLength({ max: 50 }).withMessage('Bộ phận không được vượt quá 50 ký tự.'),

body('years_of_experience')
.if(body('role').equals('professor'))
.notEmpty().withMessage('Số năm kinh nghiệm là bắt buộc cho vai trò giáo sư.')
.isInt({ min: 0 }).withMessage('Số năm kinh nghiệm phải là số nguyên không âm.'),

body('password')
.notEmpty().withMessage('Mật khẩu là bắt buộc.')
.isLength({ min: 6 }).withMessage('Mật khẩu phải có ít nhất 6 ký tự.')
.matches(/[A-Z]/).withMessage('Mật khẩu phải có ít nhất một ký tự chữ hoa.')
.matches(/[0-9]/).withMessage('Mật khẩu phải có ít nhất một số.'),

body('identity_card')
.notEmpty().withMessage('Chứng minh thư là bắt buộc.')
.isLength({ min: 9, max: 12 }).withMessage('Chứng minh thư phải có từ 9 đến 12 ký tự.'),

];
27 changes: 27 additions & 0 deletions src/public/js/section.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ function confirmSectionDelete() {

let courseIdToDelete = null;

function showSections(courseId) {
document.getElementById(`sections-${courseId}`).classList.remove('hidden');
}
function hideSections(courseId) {
document.getElementById(`sections-${courseId}`).classList.add('hidden');
}

function showDeleteForm(id) {
courseIdToDelete = id;
$('#deleteModal').removeClass('hidden');
Expand Down Expand Up @@ -104,3 +111,23 @@ function confirmDelete() {
}
}

function addSectionForm() {
const container = document.getElementById('sectionsContainer');
const newForm = document.createElement('div');
newForm.className = 'section-form';
newForm.innerHTML = `
<label for="name">Section Name</label>
<input type="text" name="name[]" required>
<label for="edit-courseId">Course</label>
<select name="course_id[]" required>
${courses.map(course => `<option value="${course.id}">${course.name}</option>`).join('')}
</select>
<label for="total_time">Total Time</label>
<input type="number" name="total_time[]" required>
<label for="total_lesson">Total Lesson</label>
<input type="number" name="total_lesson[]" required>
<button type="button" class="remove-btn" onclick="removeSectionForm(this)">Xóa</button>
`;
container.appendChild(newForm);
}

4 changes: 2 additions & 2 deletions src/routes/user.routes.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { Router } from "express";
import * as userController from "../controller/user.controller";

const { registerValidation } = require('../entity/dto/register.dto');
const router: Router = Router();

router.get("/signup", (req, res) => {
res.render("signup", { title: req.t("home.signup"), pageUrl: "/signup" });
});

router.post("/register", userController.register);
router.post("/register", registerValidation, userController.register);

router.get("/login", (req, res) => {
res.render("login", { title: req.t("home.login"), pageUrl: "/login" });
Expand Down
28 changes: 1 addition & 27 deletions src/views/professor/courseManagement.pug
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,6 @@ block content
.btn-group-admin
.confirmDelete-btn: button(onclick="confirmSectionDelete()") #{t('admin.confirm-delete')}
.cancel-btn: button(type="button" onclick="hideSectionDeleteForm()") #{t('admin.cancel')}
script.
function showSections(courseId) {
document.getElementById(`sections-${courseId}`).classList.remove('hidden');
}
function hideSections(courseId) {
document.getElementById(`sections-${courseId}`).classList.add('hidden');
}

<!-- Create Form -->
#createModal.hidden
Expand Down Expand Up @@ -230,23 +223,4 @@ block content
.cancel-btn: button(type="button" onclick="hideDeleteForm()") #{t('admin.cancel')}

script.
const courses = JSON.parse('!{JSON.stringify(courses)}');
function addSectionForm() {
const container = document.getElementById('sectionsContainer');
const newForm = document.createElement('div');
newForm.className = 'section-form';
newForm.innerHTML = `
<label for="name">Section Name</label>
<input type="text" name="name[]" required>
<label for="edit-courseId">Course</label>
<select name="course_id[]" required>
${courses.map(course => `<option value="${course.id}">${course.name}</option>`).join('')}
</select>
<label for="total_time">Total Time</label>
<input type="number" name="total_time[]" required>
<label for="total_lesson">Total Lesson</label>
<input type="number" name="total_lesson[]" required>
<button type="button" class="remove-btn" onclick="removeSectionForm(this)">Xóa</button>
`;
container.appendChild(newForm);
}
const courses = JSON.parse('!{JSON.stringify(courses)}');
26 changes: 21 additions & 5 deletions src/views/signup.pug
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ block content
button.ms-2.mb-1.btn-close(type='button' data-bs-dismiss='toast' aria-label='Close')
.toast-body
| #{t('signup.signup-success-msg')}

#toastNoAutohideError.toast(role='alert' aria-live='assertive' aria-atomic='true' data-bs-delay="2000" style='opacity: 1; display: none')
.toast-header.text-danger
i(data-feather='alert-octagon').me-2
Expand All @@ -28,6 +29,19 @@ block content
form#registerForm.shadow.p-4.custom-width(action='/register' method='POST')
.text-center.wow.fadeInUp(data-wow-delay='0.1s')
h1.mb-5.bg-white.text-center.px-3 #{t('home.signup')}

.row.g-3
if errors && errors.length > 0
.col-12
.alert.alert-danger
p Vui lòng sửa lỗi:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I18n text

if (role === 'professor')
if errors.some(error => error.msg.includes('Bộ phận') || error.msg.includes('Số năm kinh nghiệm'))
each error in errors
p= error.msg
each error in errors
p= error.msg

.row.g-3
.col-12
.form-floating
Expand Down Expand Up @@ -63,11 +77,11 @@ block content
option(value='professor') #{t('admin-user.professor')}
label(for='role') #{t('signup.role')}
.col-12.form-floating.department-field(style='display: none;')
input#department.form-control(type='text' placeholder='Department' name='department')
label(for='department') #{t('signup.department')}
input#department.form-control(type='text' placeholder='Department' name='department')
label(for='department') #{t('signup.department')}
.col-12.form-floating.years-experience-field(style='display: none;')
input#years_of_experience.form-control(type='number' placeholder='Years of Experience' name='years_of_experience')
label(for='years_of_experience') #{t('signup.years-of-experience')}
input#years_of_experience.form-control(type='number' placeholder='Years of Experience' name='years_of_experience')
label(for='years_of_experience') #{t('signup.years-of-experience')}
.col-12
.form-floating
input#password.form-control(type='password' placeholder='Password' name='password' required)
Expand All @@ -89,6 +103,7 @@ block content
<!-- Signup End -->

include partial/footer

script.
document.querySelector("#registerForm").addEventListener("submit", async function(event) {
event.preventDefault();
Expand All @@ -106,7 +121,6 @@ block content
additional_info: formData.get("additional_info"),
department: formData.get("department"),
years_of_experience: formData.get("years_of_experience"),

};

try {
Expand All @@ -127,11 +141,13 @@ block content
} catch (error) {
const toastElement = document.getElementById("toastNoAutohideError");
toastElement.style.removeProperty("display");
toastElement.querySelector('.toast-body').textContent = error.responseJSON.errors[0].msg; // Chỉ hiển thị lỗi đầu tiên
setTimeout(() => {
toastElement.style.display = "none";
}, 2000);
}
});

document.querySelector("#role").addEventListener("change", function () {
const isProfessor = this.value === "professor";
document.querySelector(".department-field").style.display = isProfessor ? "block" : "none";
Expand Down