Home > other >  How to use regex on password's validation with React?
How to use regex on password's validation with React?

Time:05-16

I'm trying to use regex for the first time but it doesn't works. I'd like to put a regex on password when the user creates an account. I use Redux and middlewares. I've got a component Subscribe where I wrote my regex but maybe I have to do this in the user middleware with the POST request ...? Here is my code :

USER ACTIONS :

export const CHANGE_PASSWORD = 'CHANGE_PASSWORD';
export const CHANGE_EMAIL = 'CHANGE_EMAIL';
export const CHANGE_PSEUDO = 'CHANGE_PSEUDO';
export const SET_FLASH_MESSAGE_FOR_SUBSCRIBE = 'SET_FLASH_MESSAGE_FOR_SUBSCRIBE';
export const CREATE_USER = 'CREATE_USER';
export const changePassword = (newValue) => ({
  type: CHANGE_PASSWORD,
  value: newValue,
});
export const changeEmail = (newValue) => ({
  type: CHANGE_EMAIL,
  value: newValue,
});
export const changePseudo = (newValue) => ({
  type: CHANGE_PSEUDO,
  value: newValue,
});
export const setFlashMessageForSubscribe = (flashMessage) => ({
  type: SET_FLASH_MESSAGE_FOR_SUBSCRIBE,
  flashMessage: flashMessage,
});
export const createUser = () => ({
  type: CREATE_USER,
});

USER REDUCER :

import {
  CHANGE_EMAIL,
  CHANGE_PASSWORD,
  SET_FLASH_MESSAGE_FOR_SUBSCRIBE,
  CHANGE_PSEUDO,
} from '../actions/user';

export const initialState = {

  email: '',
  password: '',
  flashMessage: '',
};

const user = (state = initialState, action = {}) => {
  switch (action.type) {
    case CHANGE_EMAIL:
      return {
        ...state,
        email: action.value,
      };
    case CHANGE_PASSWORD:
      return {
        ...state,
        password: action.value,
      };
    case CHANGE_PSEUDO:
      return {
        ...state,
        username: action.value,
      };
    case SET_FLASH_MESSAGE_FOR_SUBSCRIBE:
      return {
        ...state,
        flashMessage: action.flashMessage,
      };
    default:
      return state;
  }
};
export default user;

USER MIDDLEWARE :

import axios from 'axios';
import jwt from 'jwt-decode';

import {
  setFlashMessageForSubscribe,
  CREATE_USER,
} from '../actions/user';

const userMiddleware = (store) => (next) => (action) => {
  switch (action.type) {
    case CREATE_USER:
      axios.post(
        // URL
        'http://laure-chapert.vpnuser.lan:8000/api/user/create',
        {
          email: store.getState().user.email,
          password: store.getState().user.password,
          username: store.getState().user.username,
        },
      )
        .then((response) => {
          // eslint-disable-next-line prefer-destructuring
          console.log(response);
          if (response.status === 201) {
            const validationMessage = 'Your account has been created';
            store.dispatch(setFlashMessageForSubscribe(validationMessage));
          }
        })
        .catch((error) => {
          console.log(error);
        });
      break;
    default:
      break;
  }
  next(action);
};

export default userMiddleware;

SUBSCRIBE COMPONENT

import {
  Form,
  Button,
  Alert,
} from 'react-bootstrap';
import { useSelector, useDispatch } from 'react-redux';
import {
  changeEmail,
  changePassword,
  changePseudo,
  createUser,
  setFlashMessageForSubscribe,
} from '../../actions/user';

// import styles
import './subscribe.scss';

const Subscribe = () => {
  const emailValue = useSelector((state) => state.user.email);
  const passwordValue = useSelector((state) => state.user.password);
  const username = useSelector((state) => state.user.username);
  const flashMessage = useSelector((state) => state.user.flashMessage);
  const dispatch = useDispatch();
  return (
    <div>
      <div className="subscribe-form">
        { flashMessage !== '' && <Alert variant="success">{flashMessage}</Alert> }
        <h2 className="subscribe-title">Subscribe</h2>
        <Form>
          <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
            <Form.Label>Pseudo</Form.Label>
            <Form.Control
              type="pseudo"
              placeholder="Anthony"
              pseudo={username}
              onChange={(event) => {
                dispatch(changePseudo(event.target.value));
              }}
            />
          </Form.Group>
          <Form.Group className="mb-3" controlId="exampleForm.ControlInput2">
            <Form.Label>Email</Form.Label>
            <Form.Control
              type="email"
              placeholder="[email protected]"
              email={emailValue}
              onChange={(event) => {
                dispatch(changeEmail(event.target.value));
              }}
            />
          </Form.Group>
          <Form.Group className="mb-3" controlId="exampleForm.ControlInput3">
            <Form.Label>Password</Form.Label>
            <Form.Control
              type="password"
              password={passwordValue}
              onChange={(event) => {
                dispatch(changePassword(event.target.value));
              }}
            />
          </Form.Group>
        </Form>
        <Button
          variant="primary"
          onClick={() => {
            if (passwordValue.matches('^(?=.*[A-Za-z])(?=.*d)[A-Za-zd]{8,}$')) {
              dispatch(createUser());
            }
            else {
              const validationMessage = 'Your password must contain at least one letter and one number';
              dispatch(setFlashMessageForSubscribe(validationMessage));
            }
          }}
        >
          Valider
        </Button>
      </div>
    </div>
  );
};

export default Subscribe;

I add that registration works very well without regex. This is a security feature that I would like to add. Thank you very much!

CodePudding user response:

try this :

<Form.Control
              type="password"
              password={passwordValue}
              onChange={(event) => {
               let regex = = new RegExp('^(?=.*[A-Za-z])(?=.*d)[A-Za-zd]{8,}$')
              if(regex.test(event.target.value)){
                dispatch(changePassword(event.target.value));
             }else{
              ...do something
              }
              }}
            />

CodePudding user response:

I tried this but event when the password respects the regex rule, the flashMessage is displayed. I'd like to put this in the middleware .. Any ideas?

<Button
          variant="primary"
          onClick={() => {
            const regex = ('^(?=.*[A-Za-z])(?=.*d)[A-Za-zd]{8,}$');
            if (regex.test) {
              dispatch(createUser());
            }
            else {
              dispatch(setFlashMessageForSubscribe('Your password should contain a letter and a number'));
            }
          }}
        >
          Valider
        </Button>
  • Related