0% found this document useful (0 votes)
4 views13 pages

Registration Form with Validation

Basics of html

Uploaded by

chianji622
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

Registration Form with Validation

Basics of html

Uploaded by

chianji622
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

<!

DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Form (CDN)</title>
<link rel="stylesheet" href="[Link]">
<script src="[Link]
<script src="[Link]
script>
<script src="[Link]
<style>
.error-message {
color: red;
font-size: 0.85em;
margin-top: 5px;
}

.password-strength-container {
width: 100%;
background-color: #e0e0e0;
border-radius: 8px;
/* Slightly larger border-radius */
margin-top: 10px;
height: 15px;
/* Increased height for better visibility */
overflow: hidden;
position: relative;
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
/* Subtle inner shadow for depth */
}

.password-strength-bar {
height: 100%;
border-radius: 8px;
/* Match container border-radius */
transition: width 0.3s ease-in-out, background-color 0.3s ease-in-out;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
/* Subtle shadow for the bar itself */
}

.password-strength-text {
font-size: 0.85em;
/* Slightly larger font size */
color: #333;
/* Darker color for better contrast */
margin-top: 5px;
display: block;
text-align: right;
font-weight: bold;
/* Make text bold */
}

.password-strength-interpretation {
font-size: 0.85em;
color: #555;
margin-top: 5px;
display: block;
text-align: left;
font-weight: bold;
}

.offline-message {
background-color: #ffdddd;
color: #d8000c;
padding: 10px;
text-align: center;
font-weight: bold;
border: 1px solid #d8000c;
margin-bottom: 15px;
border-radius: 5px;
}
</style>
</head>

<body>
<div id="root"></div>

<script type="text/babel">
const { useState, useEffect } = React;

function Header() {
return (
<header className="main-header">
<img src="[Link]" alt="Site Logo" className="site-
logo" />
<span className="site-title">CNPS"

"</span>
</header>
);
}

function SideNav() {
return (
<nav className="side-nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Winners</a></li>
<li><a href="#">Teams</a></li>
<li><a href="#">Schedule</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
);
}

function Modal({ show, title, message, onConfirm, onCancel }) {


if (!show) {
return null;
}

return (
<div className="modal-overlay">
<div className="modal-box">
<h2>{title}</h2>
<pre id="modalInfo" style={{
whiteSpace: 'pre-wrap',
fontFamily: '\'Gill Sans\', \'Gill Sans MT\',
Calibri, \'Trebuchet MS\', sans-serif'
}}>{message}</pre>
<div className="modal-actions">
<button id="modalCancel"
onClick={onCancel}>Cancel</button>
<button id="modalOk"
onClick={onConfirm}>Confirm</button>
</div>
</div>
</div>
);
}

function RegistrationForm() {
const [formData, setFormData] = useState({
name: '',
phoneNumber: '',
email: '',
poBox: '',
dateOfBirth: '',
password: '',
confirmPassword: '', // New state for confirm password
termsAccepted: false, // New state for terms acceptance
newsletterOptIn: false, // New state for newsletter opt-in
});
const [showPassword, setShowPassword] = useState(false);
const [showModal, setShowModal] = useState(false);
const [modalMessage, setModalMessage] = useState('');

// New state for validation errors


const [nameError, setNameError] = useState('');
const [phoneNumberError, setPhoneNumberError] = useState('');
const [emailError, setEmailError] = useState('');
const [poBoxError, setPoBoxError] = useState('');
const [dateOfBirthError, setDateOfBirthError] = useState('');
const [passwordError, setPasswordError] = useState('');
const [confirmPasswordError, setConfirmPasswordError] =
useState(''); // New state for confirm password error
const [termsError, setTermsError] = useState(''); // New state for
terms error

// New state for password strength


const [passwordStrength, setPasswordStrength] = useState(0);

// Function to calculate password strength


const calculatePasswordStrength = (password) => {
let strength = 0;
const length = [Link];

// Length score
if (length >= 8) strength += 20;
if (length >= 12) strength += 20;
if (length >= 16) strength += 10; // Max 50 for length

// Character type scores


if (/[A-Z]/.test(password)) strength += 12; // Uppercase
if (/[a-z]/.test(password)) strength += 12; // Lowercase
if (/\d/.test(password)) strength += 12; // Numbers
if (/[\W_]/.test(password)) strength += 12; // Special characters
(W_ includes underscore)

// Cap the strength at 99%


return [Link](strength, 99);
};

// Function to get textual interpretation of password strength


const getPasswordStrengthText = (strength) => {
if (strength === 0) return ''; // No password entered
if (strength <= 20) return 'Very Weak';
if (strength <= 40) return 'Weak';
if (strength <= 60) return 'Moderate';
if (strength <= 80) return 'Strong';
return 'Very Strong';
};

const handleChange = (e) => {


const { name, value, type, checked } = [Link];
setFormData((prevData) => ({
...prevData,
[name]: type === 'checkbox' ? checked : value,
}));

// Real-time validation based on the input field


switch (name) {
case 'name':
if (!/^[A-Za-z0-9]*$/.test(value)) {
setNameError('Name can only contain letters and
numbers.');
} else {
setNameError('');
}
break;
case 'phoneNumber':
if (!/^\d{0,9}$/.test(value)) {
setPhoneNumberError('Phone number must be 9 digits.');
} else {
setPhoneNumberError('');
}
break;
case 'email':
// Basic email validation for real-time feedback
if (value && ([Link]('@') <= 0 || [Link]('@')
=== [Link] - 1)) {
setEmailError('Please enter a valid email address.');
}
else if ([Link] > 0 && !/^[\w.-]+@[\w.-]+\.[a-zA-Z]
{2,6}$/.test(value)) {
setEmailError('Please enter a valid email address.');
} else {
setEmailError('');
}
break;
case 'poBox':
if (!/^\d{0,6}$/.test(value)) {
setPoBoxError('P.O. Box must be 2 to 6 digits.');
} else {
setPoBoxError('');
}
break;
case 'dateOfBirth':
if (value) {
const birthDate = new Date(value);
const birthYear = [Link]();
const today = new Date();
[Link](0, 0, 0, 0);

if (birthYear < 1910) {


setDateOfBirthError('Birth year must be 1910 or
later.');
} else if (birthDate > today) {
setDateOfBirthError('Date of birth cannot be in the
future.');
} else {
setDateOfBirthError('');
}
} else {
setDateOfBirthError('');
}
break;
case 'password':
// Password validation for real-time feedback (less strict
than final submit)
if ([Link] > 0 && !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?
=.*[\W_]).{8,}$/.test(value)) {
setPasswordError('Password must be at least 8 chars,
with uppercase, lowercase, number, and special char.');
} else {
setPasswordError('');
}
// Update password strength
setPasswordStrength(calculatePasswordStrength(value));
// Also validate confirm password if password changes
if ([Link] && value !==
[Link]) {
setConfirmPasswordError('Passwords do not match.');
} else {
setConfirmPasswordError('');
}
break;
case 'confirmPassword':
if (value !== [Link]) {
setConfirmPasswordError('Passwords do not match.');
} else {
setConfirmPasswordError('');
}
break;
case 'termsAccepted':
if (!checked) {
setTermsError('You must accept the terms and
conditions.');
} else {
setTermsError('');
}
break;
default:
break;
}
};

const handleTogglePassword = () => {


setShowPassword(!showPassword);
};

const autofillPassword = () => {


const name = [Link]().toLowerCase();
const email = [Link]().toLowerCase();

// Only attempt to autofill if both name and email are provided


if (name && email) {
const userKey = `${name}|${email}`;
const savedPassword = [Link](userKey);
if (savedPassword) {
setFormData((prevData) => ({ ...prevData, password:
savedPassword, confirmPassword: savedPassword })); // Autofill confirm password too

setPasswordStrength(calculatePasswordStrength(savedPassword)); // Update strength


for autofilled password
}
}
};

const handleSubmit = (e) => {


[Link]();

const { name, phoneNumber, email, poBox, dateOfBirth, password,


confirmPassword, termsAccepted, newsletterOptIn } = formData;

// Re-validate all fields on submit to catch any missed errors or


final checks
let isValid = true;

// Name validation
if (!/^[A-Za-z0-9]+$/.test(name)) {
setNameError('Name can only contain letters and numbers (no
spaces or special characters).');
isValid = false;
} else {
setNameError('');
}

// Phone validation
if (!/^\d{9}$/.test(phoneNumber)) {
setPhoneNumberError('Please enter exactly 9 digits (numbers
only).');
isValid = false;
} else {
setPhoneNumberError('');
}

// Email validation
const atIndex = [Link]('@');
if (atIndex <= 0 || atIndex === [Link] - 1) {
setEmailError('Please enter a valid email address with "@" not
at the start or end.');
isValid = false;
} else {
setEmailError('');
}

// P.O. Box validation


if (!/^\d{2,6}$/.test(poBox)) {
setPoBoxError('P.O. Box number must be between 2 and 6
digits.');
isValid = false;
} else {
setPoBoxError('');
}

// Date of Birth validation


if (dateOfBirth) {
const birthDate = new Date(dateOfBirth);
const birthYear = [Link]();
const today = new Date();
[Link](0, 0, 0, 0);

if (birthYear < 1910) {


setDateOfBirthError('Please enter a birth year of 1910 or
later.');
isValid = false;
} else if (birthDate > today) {
setDateOfBirthError('Date of birth cannot be in the
future.');
isValid = false;
} else {
setDateOfBirthError('');
}
} else {
setDateOfBirthError('Date of Birth is required.'); // Added
required check for DOB
isValid = false;
}

// Password validation
if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).
{8,}$/.test(password)) {
setPasswordError('Password must be at least 8 characters long
and include uppercase, lowercase, number, and special character.');
isValid = false;
} else {
setPasswordError('');
}

// Confirm Password validation


if (password !== confirmPassword) {
setConfirmPasswordError('Passwords do not match.');
isValid = false;
} else {
setConfirmPasswordError('');
}

// Terms and Conditions validation


if (!termsAccepted) {
setTermsError('You must accept the terms and conditions.');
isValid = false;
} else {
setTermsError('');
}

if (!isValid) {
// If any validation fails, prevent form submission
alert('Please correct the errors in the form.');
return;
}

const info = `\nName: ${name}\nPhone: ${phoneNumber}\nEmail: $


{email}\nP.O. Box: ${poBox}\nDate of Birth: ${dateOfBirth}\nPassword: $
{'*'.repeat([Link])}\nTerms Accepted: ${termsAccepted ? 'Yes' : 'No'}\
nNewsletter Opt-in: ${newsletterOptIn ? 'Yes' : 'No'}
`;
setModalMessage(info);
setShowModal(true);
};

const handleModalConfirm = () => {


const { name, email, password } = formData;
const userKey = `${[Link]()}|${[Link]()}`;
[Link](userKey, password);
setShowModal(false);
alert('Form submitted and data saved!');
};

const handleModalCancel = () => {


setShowModal(false);
};

const handleReset = () => {


setFormData({
name: '',
phoneNumber: '',
email: '',
poBox: '',
dateOfBirth: '',
password: '',
confirmPassword: '',
termsAccepted: false,
newsletterOptIn: false,
});
setShowPassword(false);
// Clear all errors on reset
setNameError('');
setPhoneNumberError('');
setEmailError('');
setPoBoxError('');
setDateOfBirthError('');
setPasswordError('');
setConfirmPasswordError(''); // Clear confirm password error
setTermsError(''); // Clear terms error
setPasswordStrength(0); // Reset password strength
};

return (
<div className="container">
<div className="card">
<h2>Registration Form</h2>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name:</label>
<input
type="text"
name="name"
id="name"
placeholder="Enter your name here. Please Enter
only Text"
required
value={[Link]}
onChange={handleChange}
onBlur={autofillPassword}
/>
{nameError && <span className="error-
message">{nameError}</span>}
</div>

<div className="form-group">
<label htmlFor="phoneNumber">Phone Number:</label>
<input
type="tel"
name="phoneNumber"
id="phoneNumber"
placeholder="Please Enter only Numbers (+237)"
required
value={[Link]}
onChange={handleChange}
/>
{phoneNumberError && <span className="error-
message">{phoneNumberError}</span>}
</div>

<div className="form-group">
<label htmlFor="email">Email:</label>
<input
type="email"
name="email"
id="email"
placeholder="Email here"
required
value={[Link]}
onChange={handleChange}
onBlur={autofillPassword}
/>
{emailError && <span className="error-
message">{emailError}</span>}
</div>

<div className="form-group">
<label htmlFor="poBox">P.O. Box :</label>
<input
type="text"
name="poBox"
id="poBox"
placeholder="Enter The numbers"
required
value={[Link]}
onChange={handleChange}
/>
{poBoxError && <span className="error-
message">{poBoxError}</span>}
</div>

<div className="form-group">
<label htmlFor="dateOfBirth">Date Of Birth:</label>
<input
type="date"
name="dateOfBirth"
id="dateOfBirth"
placeholder="Please Enter a valid date in the
format YYYY-MM-DD"
required
value={[Link]}
onChange={handleChange}
/>
{dateOfBirthError && <span className="error-
message">{dateOfBirthError}</span>}
</div>

<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type={showPassword ? 'text' : 'password'}
name="password"
id="password"
className="password-input"
placeholder="Enter a strong password"
required
value={[Link]}
onChange={handleChange}
/>
<input
type="checkbox"
id="togglePassword"
style={{ marginTop: '10px' }}
checked={showPassword}
onChange={handleTogglePassword}
/>
<label htmlFor="togglePassword" style={{ fontSize:
'0.95rem', cursor: 'pointer' }}>
Show Password
</label>
{passwordError && <span className="error-
message">{passwordError}</span>}

{/* Password Strength Bar */}


<div className="password-strength-container">
<div
className="password-strength-bar"
style={{
width: `${passwordStrength}%`,
backgroundColor: passwordStrength <
40 ? 'red' : passwordStrength < 70 ? 'orange' : 'green'
}}
></div>
</div>
<span className="password-strength-
text">{passwordStrength}%</span>
<span className="password-strength-
interpretation">{getPasswordStrengthText(passwordStrength)}</span>
</div>

<div className="form-group">
<label htmlFor="confirmPassword">Confirm
Password:</label>
<input
type={showPassword ? 'text' : 'password'}
name="confirmPassword"
id="confirmPassword"
className="password-input"
placeholder="Confirm your password"
required
value={[Link]}
onChange={handleChange}
/>
{confirmPasswordError && <span className="error-
message">{confirmPasswordError}</span>}
</div>

<div className="form-group checkbox-group">


<input
type="checkbox"
name="termsAccepted"
id="termsAccepted"
checked={[Link]}
onChange={handleChange}
/>
<label htmlFor="termsAccepted">
I agree to the <a href="#" target="_blank"
rel="noopener noreferrer">Terms and Conditions</a>
</label>
{termsError && <span className="error-
message">{termsError}</span>}
</div>

<div className="form-group checkbox-group">


<input
type="checkbox"
name="newsletterOptIn"
id="newsletterOptIn"
checked={[Link]}
onChange={handleChange}
/>
<label htmlFor="newsletterOptIn">Subscribe to
newsletter</label>
</div>

<button type="reset" id="reset" onClick={handleReset}>


Reset
</button>

<button type="submit" id="submit">


Submit
</button>
</form>
</div>
<Modal
show={showModal}
title="Confirm Your Information"
message={modalMessage}
onConfirm={handleModalConfirm}
onCancel={handleModalCancel}
/>
</div>
);
}

function App() {
const [isOnline, setIsOnline] = useState([Link]);

useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);

[Link]('online', handleOnline);
[Link]('offline', handleOffline);

return () => {
[Link]('online', handleOnline);
[Link]('offline', handleOffline);
};
}, []);

return (
<div className="App">
{!isOnline && (
<div className="offline-message">
You are currently offline. Please check your internet
connection.
</div>
)}
<Header />
<SideNav />
<h1>Document Form</h1>
<RegistrationForm />
</div>
);
}

const root = [Link]([Link]('root'));


[Link](<App />);
</script>
</body>

</html>
<?php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$box = $_POST['pobox'];
$dob = $_POST['dateofbirth'];
$password = $_POST['password'];

// Database connect

$conn = new mysqli('localhost', 'root', '', 'tested');


if($conn->connect_error){
die('connectio failed : ' .$conn->connect_error);

}
else {

$stmt = $conn->prepare("INSERT INTO registrations(names, phone,


po, dates, passwords, email)
VALUES(?, ?, ?, ?, ?, ?)");
$stmt->bind_param("siisss",$name, $phone,
$box, $dob, $password, $email);

$stmt->execute();
echo "registration successful!!";

$stmt->close();
$conn->close();

}
?>

You might also like