Skip to content

Commit

Permalink
Merge pull request #118 from KashishJuneja101003/main
Browse files Browse the repository at this point in the history
Real-time Email Validation for Signup Form
  • Loading branch information
avanimathur authored Jan 11, 2025
2 parents defe3ba + 00f8860 commit 3037c60
Show file tree
Hide file tree
Showing 5 changed files with 169 additions and 6 deletions.
14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "your-app-name",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"scripts": {
"start": "node signup_server.js"
},
"dependencies": {
"express": "^4.17.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5"
}
}
7 changes: 7 additions & 0 deletions sign_up.css
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,10 @@ form {
padding: 0;
}

.error-message {
color: red;
font-size: 14px;
margin-top: 5px;
}


23 changes: 17 additions & 6 deletions sign_up.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,29 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="sign_up.css">
<title>Sign up|Studentify</title>

</head>
<body>
<form action="action_page.php" style="border: 1px solid #ccc">
<form id="signupForm" action="http://localhost:3000/signup" method="post" style="border: 1px solid #ccc">
<div class="container">
<h1 align="center">Sign Up</h1>
<p align="center">Please fill in this form to create an account.</p>
<h1 style="display: flex; justify-content:center;">Sign Up</h1>
<p style="display: flex; justify-content:center;">Please fill in this form to create an account.</p>
<hr />

<!-- Error msg display -->
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required />
<input type="text" placeholder="Enter Email" name="email" id="email" required />
<span id="emailError" class="error-message"></span><br><br>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required />
<input type="password" placeholder="Enter Password" name="password" id="password" required />
<span id="passwordError" class="error-message"></span><br><br>

<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required />
<input type="password" placeholder="Repeat Password" name="repeatPassword" id="repeatPassword" required />
<span id="repeatPasswordError" class="error-message"></span><br><br>



<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom: 15px" />
Expand All @@ -38,5 +45,9 @@ <h1 align="center">Sign Up</h1>
</div>
</div>
</form>


<script src="./sign_up.js" defer></script>

</body>
</html>
71 changes: 71 additions & 0 deletions sign_up.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
document.getElementById('signupForm').addEventListener('submit', function (e) {
e.preventDefault();

const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const repeatPassword = document.getElementById('repeatPassword').value;

// Reset previous error messages
document.getElementById('emailError').innerText = '';
document.getElementById('passwordError').innerText = '';
document.getElementById('repeatPasswordError').innerText = '';

// Validate if fields are empty
if (!email || !password || !repeatPassword) {
alert('Please fill in all fields.');
return; // Stop further execution if any field is empty
}

let isValid = true;

// Email validation
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!emailPattern.test(email)) {
document.getElementById('emailError').innerText = 'Please enter a valid email address.';
isValid = false;
}

// Password validation
if (password.length < 6) {
document.getElementById('passwordError').innerText = 'Password must be at least 6 characters.';
isValid = false;
}

// Repeat Password validation
if (password !== repeatPassword) {
document.getElementById('repeatPasswordError').innerText = 'Passwords do not match.';
isValid = false;
}

// If all validations pass, submit the form using Fetch API
if (isValid) {
// Create URL-encoded string
const formData = new URLSearchParams();
formData.append('email', email);
formData.append('password', password);
formData.append('repeatPassword', repeatPassword);

fetch('http://localhost:3000/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded', // Explicitly set the content type
},
body: formData.toString(), // Serialize the form data
})
.then(response => response.json())
.then(data => {
// Show alert based on response from the server
if (data.message === 'Account created successfully!') {
alert('Registration successful!');
} else if (data.message === 'Email is already registered.') {
alert('This email is already registered.');
} else {
alert('Error: ' + data.message);
}
document.getElementById('signupForm').reset();
})
.catch(error => {
alert('An error occurred. Please try again.');
});
}
});
60 changes: 60 additions & 0 deletions signup_server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';

const app = express();

// Enable CORS
app.use(cors());

// Middleware to parse URL-encoded data (FormData)
app.use(bodyParser.urlencoded({ extended: true }));

// Middleware to parse JSON data
app.use(bodyParser.json());

const users = []; // Dummy user storage

app.post('/signup', (req, res) => {
console.log('\nReceived data:', req.body);
const { email, password, repeatPassword } = req.body;

// Check if all fields are present
if (!email || !password || !repeatPassword) {
return res.status(400).json({ message: 'Please fill in all fields.' });
}

// Validate email format
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!emailPattern.test(email)) {
return res.status(400).json({ message: 'Please enter a valid email address.' });
}

// Password length check
if (password.length < 6) {
return res.status(400).json({ message: 'Password must be at least 6 characters.' });
}

// Password match check
if (password !== repeatPassword) {
return res.status(400).json({ message: 'Passwords do not match.' });
}

// Check if email already exists
if (users.some(user => user.email === email)) {
console.log('\n'+email+' is already registered!');
return res.status(400).json({ message: 'Email is already registered.' });
}

// Add user to the users array
users.push({ email, password });

// Respond with success message
res.status(201).json({ message: 'Account created successfully!' });
console.log('\n'+email+' is registered successfully!');
});

app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});

0 comments on commit 3037c60

Please sign in to comment.