Vue simple registration page + send verification code function implementation example

Vue simple registration page + send verification code function implementation example

1. Effect display

insert image description here

insert image description here

2. Enhanced verification code and email push management (see later blog)

insert image description here

insert image description here

3. General idea

Analyze the steps of registration from the user's perspective :

  • Fill in your email address
  • Click the "Send Verification Code" button
  • Receive verification code in email
  • Fill in the remaining registration information and enter the verification code
  • Registration successful!

Analyze the steps from the perspective of a system designer :

  • The system randomly generates six digits
  • Send the verification code to the email address provided by the user
  • Verify the verification code based on the information provided by the user
  • If the verification is successful, the data will be entered and the user registration will be successful!

4. Preliminary preparation

Enable POP3/SMTP service in QQ mailbox

Here you can refer to

https://www.jb51.net/qq/321090.html

5. Front-end code

<template>
  <div class="rg_layout">
    <div class="rg_left">
      <p>New User Registration</p>
      <p>USER REGISTER</p>
    </div>
    <div class="rg_center">
      <div class="rg_form">
        <div style="margin: 50px 0;"></div>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="Email" prop="Email">
            <el-col :span="15">
              <el-input placeholder="Please enter your email address" v-model="form.Email"></el-input>
            </el-col>
            <el-col :span="9">
              <el-button type="success" plain @click="sendEmail">Send email verification</el-button>
            </el-col>
          </el-form-item>
          <el-form-item label="Username">
            <el-col :span="20">
              <el-input placeholder="Please enter your username" v-model="form.username"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="Password">
            <el-input placeholder="Please enter your password" v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="Gender">
            <el-col :span="5">
              <el-radio v-model="form.radio" label="1">Male</el-radio>
            </el-col>
            <el-col :span="3">
              <el-radio v-model="form.radio" label="2">Female</el-radio>
            </el-col>
          </el-form-item>
          <el-form-item label="Date of Birth">
            <el-col :span="15">
              <el-date-picker type="date" placeholder="Select date" v-model="form.date" style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="Verification code">
            <el-col :span="15">
              <el-input
                  type="text"
                  placeholder="The verification code will be sent to your email"
                  v-model="form.text"
                  oninput="value=value.replace(/\D/g,'')"
                  maxlength="6"
                  show-word-limit
              >
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="20">
              <el-button type="primary" @click="onSubmit">Register now</el-button>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="rg_right">
      <p>Already have an account?
        <el-link icon="el-icon-user-solid" type="primary" @click="login_asd">Log in now</el-link>
      </p>
    </div>

  </div>

</template>

<script>
import axios from "axios";
export default {
  mounted() {
    this.$store.state.yesOrNo = false
  },
  name: "signUp",
  data: function () {
    return {
      form: {
        Email: '',
        username: "",
        password: "",
        radio: '1',
        date: '',
        text: ''
      },
      rules:
        Email: [{required: true, message: 'Please enter your email', trigger: 'blur'}]
      },
      msg: ''
    }
  },
  methods: {
    login_asd(){
      this.$router.replace({path: '/login'});
    },
    open1() {
      this.$message({
        showClose: true,
        message: this.msg,
        type: 'warning'
      });
    },
    open2() {
      this.$message({
        showClose: true,
        message: this.msg,
        type: 'success'
      });
    },
    open3() {
      this.$message({
        showClose: true,
        message: this.msg,
        type: 'error'
      });
    },
    sendEmail() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let _this = this
          axios.post(this.$store.state.url+':8412/user/sendSignUpCode?email='+_this.form.Email,
              ).catch(function (error) {
                _this.msg = "The email format is incorrect!"
                _this.open1()
          }).then(function (response) {
            if (response.data.code === 200) {
              _this.msg = response.data.msg
              _this.open2()
            } else {
              _this.msg = response.data.msg
              _this.open3()
            }
          })
        }
      })
    },
    onSubmit(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          let _this = this;
          let tmp;
          if(this.form.radio === "1"){
            tmp = 'male'
          }else{
            tmp = 'female'
          }
          axios.post(this.$store.state.url+':8412/user/userSignUp?code='+_this.form.text,
              {
                email: this.form.Email,
                username: this.form.username,
                password: this.form.password,
                sex: tmp,
                birthday: this.form.date
              }
          ).catch(function (error) {
            _this.msg = "There is a problem with the email format!"
            _this.open1()
          }).then(function (response) {
            if (response.data.code === 200) {
              _this.msg = response.data.msg
              _this.open2()
              _this.$router.replace({path: '/login'});
            } else {
              _this.msg = response.data.msg
              _this.open3()
            }
          })
        }
      })
    }
  }
}
</script>


<style>
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

body {
  background-image: url(https://img-blog.csdnimg.cn/76110abf7fb84ee28c50bfbfa7fa8e11.jpg);
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: 0px -50px;
}

.rg_layout {
  width: 900px;
  height: 500px;
  border: 5px solid #EEEEEE;
  background-color: white;
  opacity: 0.8;
  /* Center the div horizontally */
  margin: auto;
  margin-top: 100px;
}

.rg_left {
  float: left;
  margin: 15px;
  width: 20%;
}

.rg_left > p:first-child {
  color: #FFD026;
  font-size: 20px;
}

.rg_left > p:last-child {
  color: #A6A6A6;
}

.rg_center {
  /*border: 1px solid red;*/
  float: left;
  width: 450px;
  /*margin: 15px;*/
}

.rg_right {
  float: right;
  margin: 15px;
}

.rg_right > p:first-child {
  font-size: 15px;
}

.rg_right pa {
  color: pink;
}

</style>

6. Backend

The framework used is springboot

① Main dependencies

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.5.2</version>
        </dependency>
        <!-- mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

② Regular verification mailbox tool class

package com.example.han.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckMail {
    public static boolean checkMail(String mail){
        Pattern pattern=Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        //\w+@(\w+.)+[az]{2,3}
        Matcher matcher = pattern.matcher(mail);
        return matcher.matches();
    }
}

③ Redis set and get tool classes

package com.example.han.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setRedisKey(String key, String value, long num) {
        System.out.println("set redis start!");
        stringRedisTemplate.opsForValue().set(key,value,num,TimeUnit.SECONDS);
        System.out.println(stringRedisTemplate.opsForValue().get(key));
    }

    public String getRedisValue(String key){
        if(!stringRedisTemplate.hasKey(key)){
            return "None";
        }
        return stringRedisTemplate.opsForValue().get(key);
    }

}

④ Core service layer code

    /**
     * Verify whether the email address is repeated* @param email email address*/
    @Override
    public ResultReturn checkEmailRepeat(String email) throws MyException {
        if (!CheckMail.checkMail(email)) {
            throw new MyException(400, "Email format error");
        }
        if (userRepository.checkEmaillRepeated(email)) {
            return ResultReturnUtil.fail(USER_EMAIL_REPEATED);
        }
        return ResultReturnUtil.success(USER_EMAIL_NOT_REPEATED, email);
    }

    /**
     * Send registration verification code* @param toEamil recipient email* @return
     */
    @Override
    public ResultReturn sendSignUpCode(String toEmail) {
        //asdasd
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(toEamil);
        simpleMailMessage.setFrom(fromEmail);
        simpleMailMessage.setSubject("Your registration verification code is here");
        Random r = new Random();
        int rate = r.nextInt(899999) + 100000;
        redisUtil.setRedisKey(toEamil + "YanZheng", rate + "", 60 * 5); //Save to redis first, key is the email address String content =
                "Hello,\n" + "\tYour verification code is:\n" + rate;
        simpleMailMessage.setText(content);
        try {
            javaMailSender.send(simpleMailMessage);
        } catch (Exception e) {
            return ResultReturnUtil.fail("Sending failed!");
        }
        return ResultReturnUtil.success("Sent successfully!", toEamil);
    }
    
    /**
     * User registration* @param userSignUpVO Basic user information required for registration* @param code Verification code sent to the email address after registration*/
    @Override
    public ResultReturn UserSignUp(UserSignUpVO userSignUpVO, int code) throws MyException {
        if (!CheckMail.checkMail(userSignUpVO.getEmail())) { //This is when the email format is wrong. throw new MyException(400, "Email format error");
        }
        if (userRepository.checkEmaillRepeated(userSignUpVO.getEmail())) { //When the email is registered repeatedly, return ResultReturnUtil.fail(USER_EMAIL_REPEATED);
        }
        String redisCode = redisUtil.getRedisValue(userSignUpVO.getEmail() + "YanZheng"); //Compare code with redis if (!redisCode.equals("" + code)) {
            return ResultReturnUtil.fail(WRONG_VERIFICATION_CODE);
        }
        UserDO user = new UserDO();
        user.setEmail(userSignUpVO.getEmail());
        user.setUsername(userSignUpVO.getUsername());
        user.setPassword(userSignUpVO.getPassword());
        user.setSex(userSignUpVO.getSex());
        user.setBirthday(userSignUpVO.getBirthday());
        if (userRepository.insertUser(user)) {
            return ResultReturnUtil.success(USER_SIGNUP_SUCCESS, user.getEmail());
        }
        return ResultReturnUtil.fail(USER_SIGNUP_FAILED);
    } 

This is the end of this article about the implementation example of Vue simple registration page + sending verification code function. For more relevant Vue registration page sending verification code content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use vue to realize the registration page effect vue to realize SMS verification code login
  • vue implements the registration function of sending SMS verification code through mobile phone
  • Example of vue+element to implement mobile phone number verification code registration

<<:  7 skills that great graphic designers need to master

>>:  How to fill items in columns in CSS Grid Layout

Recommend

Ubuntu View and modify mysql login name and password, install phpmyadmin

After installing MySQL, enter mysql -u root -p in...

JavaScript implements cool mouse tailing effects

After watching this, I guarantee that you have ha...

How to enable or disable SSH for a specific user or user group in Linux

Due to your company standards, you may only allow...

Detailed explanation of browser negotiation cache process based on nginx

This article mainly introduces the detailed proce...

Detailed Example of Row-Level Locking in MySQL

Preface Locks are synchronization mechanisms used...

How to use Typescript to encapsulate local storage

Table of contents Preface Local storage usage sce...

Getting Started with Front-End Vue Unit Testing

Table of contents 1. Why do we need unit testing?...

Excel export always fails in docker environment

Excel export always fails in the docker environme...

How to add conditional expressions to aggregate functions in MySql

MySQL filtering timing of where conditions and ha...

Three ways to configure JNDI data source in Tomcat

In my past work, the development server was gener...

Detailed basic operations on data tables in MySQL database

Table of contents 1. View the tables in the curre...

VMWare virtual machine 15.X LAN network configuration tutorial diagram

Recently, I have been working on several virtual ...

You Probably Don’t Need to Use Switch Statements in JavaScript

Table of contents No switch, no complex code bloc...

Example of using Docker Swarm to build a distributed crawler cluster

During the crawler development process, you must ...