Client and Server side form input validation

PHOTO EMBED

Sun Mar 17 2024 19:21:00 GMT+0000 (Coordinated Universal Time)

Saved by @eziokittu

// validators.jsx

// Function to validate email
export const validateEmail = (email) => {
    const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\\.,;:\s@\"]+\.)+[^<>()[\]\\.,;:\s@\"]{2,})$/i;
    return re.test(email);
};

// Function to validate password
export const validatePassword = (password) => {
    if (password.length < 8 || password.length > 32) return false;
    if (!/[A-Z]/.test(password)) return false; // At least one uppercase letter
    if (!/[a-z]/.test(password)) return false; // At least one lowercase letter
    if (!/[0-9]/.test(password)) return false; // At least one digit
    if (!/[^A-Za-z0-9]/.test(password)) return false; // At least one special character
    return true;
};


// LoginForm.jsx

import React, { useState } from 'react';
import { validateEmail, validatePassword } from './validators.jsx';

const LoginForm = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [alert, setAlert] = useState('');

    const handleSubmit = (event) => {
        event.preventDefault();
        setAlert(''); // Clear previous alerts

        // Validate inputs
        if (!validateEmail(email)) {
            setAlert('Please enter a valid email address.');
            return;
        }

        if (!validatePassword(password)) {
            setAlert('Please enter a valid password. Password must be at least 8 characters.');
            return;
        }

        // Call backend API here if validations pass
        console.log('API call here');
    };

    return (
        <div>
            {alert && (
                <div className="alert">
                    {alert}
                    <button onClick={() => setAlert('')}>Okay</button>
                </div>
            )}
            <form onSubmit={handleSubmit}>
                <label>
                    Email:
                    <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
                </label>
                <label>
                    Password:
                    <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
                </label>
                <button type="submit">Login</button>
            </form>
        </div>
    );
};

export default LoginForm;



// In your route file, e.g., authRoutes.js

const { check, validationResult } = require('express-validator');

// Define the validation chain for the password and email
const validationChain = [
    check('email')
      .normalizeEmail()
      .isEmail()
      .withMessage('Invalid email address.'),
    check('password')
      .isLength({ min: 8, max: 32 })
      .withMessage('Password must be between 8 to 32 characters long.')
      .matches(/[A-Z]/)
      .withMessage('Password must contain at least one uppercase letter.')
      .matches(/[a-z]/)
      .withMessage('Password must contain at least one lowercase letter.')
      .matches(/[0-9]/)
      .withMessage('Password must contain at least one digit.')
      .matches(/[^A-Za-z0-9]/)
      .withMessage('Password must contain at least one special character.')
];

// Add to your route, e.g., for user registration or login
app.post('/your-route', validationChain, (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, errors: errors.array() });
    }

    // Proceed with backend logic here if validation passes
});

content_copyCOPY

https://chat.openai.com/c/e49ca8a6-55e3-4648-8c33-02e68cee1123