Example of implementing dynamic verification code on a page using JavaScript

Example of implementing dynamic verification code on a page using JavaScript

introduction:

Nowadays, many dynamic verification technologies are added when users log in or register to prevent program attacks. Generally, this is achieved by asking users to enter a randomly generated verification code. I wrote one myself that does not interact with the backend, but verifies it on the front end and sends it out for everyone to see.

Effect picture:

Implementation ideas:

  • Put numbers and letters into an array, get the array index randomly, and take a total of 4 to form the verification code;
  • Render the verification codes (one by one);
  • Draw a certain number of interference lines with random colors;
  • Enter the verification code, enter 4 digits and then go to verification, a check mark will be displayed if it is correct, a cross will be displayed if it is wrong and the verification code will be refreshed.

Writing the Constructor

Text Constructor

//Text constructor function Text(o){
		this.x=0,//x coordinate this.y=0,//y coordinate this.text='',//content this.font=null;//font this.textAlign=null;//alignment		
		this.init(o);
	}
	
	Text.prototype.init=function(o){
		for(var key in o){
			this[key]=o[key];
		}
	}
	Text.prototype.render=function(context){
		this.ctx=context;
		innerRender(this);
			
		function innerRender(obj){
			var ctx=obj.ctx;
			ctx.save()
			ctx.beginPath();
			ctx.translate(obj.x,obj.y);
			
			if(obj.font){
				ctx.font=obj.font;
			}
			if (obj.textAlign) {
				ctx.textAlign=obj.textAlign;
			}
			if(obj.fill){//Is it filled? obj.fillStyle?(ctx.fillStyle=obj.fillStyle):null;
				ctx.fillText(obj.text,0,0);
			}
		 	ctx.restore();
		}
	 	return this;
	}

Line Segment Constructor

 
	//Straight line construction function Line(ctx,o){
		this.x=0,//x coordinate this.y=0,//y coordinate this.startX=0,//starting point x position this.startY=0, //starting point y position this.endX=0,//end point x position this.endY=0;//end point y position this.thin=false;//Set thinning coefficient this.ctx=ctx;
		
		this.init(o);
	}
	Line.prototype.init=function(o){
		for(var key in o){
			this[key]=o[key];
		}
	}
	Line.prototype.render = function() {
		innerRender(this);
		
		function innerRender(obj){
			var ctx=obj.ctx;
			ctx.save()
			ctx.beginPath();
			ctx.translate(obj.x,obj.y);
			if(obj.thin){
				ctx.translate(0.5,0.5);
			}
			if(obj.lineWidth){//Set line width ctx.lineWidth=obj.lineWidth;
			}
			if (obj.strokeStyle) {
				ctx.strokeStyle=obj.strokeStyle;
			}
			//Draw a line ctx.moveTo(obj.startX, obj.startY);
		 	ctx.lineTo(obj.endX, obj.endY);
		 	ctx.stroke();
		 	ctx.restore();
		}
	 	
	 	return this;
	}

Get verification code by length

	//Generate random alphanumeric characters according to the specified length Verifiable.prototype.randomWord=function(range){
	 var str = "",pos,
	   arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', ​​'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
	 for(var i=0; i<range; i++){
	  pos = Math.round(Math.random() * (arr.length-1));
	  str += arr[pos];
	 }
	 return str;
	}

Draw Text

	//Draw text Verifiable.prototype.drawText=function(){
		var that=this;
		var count = 4; //Number of characters var textW = 40; //Width of the text var code=this.code = this.randomWord(count);
		var codeArr = code.split("");
		var text,x ;
		codeArr.forEach(function(c,i){
			x = that.w/count*i+textW/2;
			//Draw text text = new Text({
				x:x,
				y:textW-10,
				text:c,
				font:'30px ans-serif',
				textAlign:'center',
				fill:true,
				fillStyle:'#412D6A'
			});
			that.renderArr.push(text);
		})		
	}

The effect at this time:

Draw interference lines

//Draw interference line Verifiable.prototype.interfering=function(){
		var count = this.lineCount=20,line,ctx=this.ctx;
		var startX,
			startY,
			endX,
			endY,
			color;
			
		for(var i=0;i<count;i++){
			//Random start coordinate, end coordinate, color startX = _.getRandom(0,140);
			startY = _.getRandom(0,40);
			endX = _.getRandom(0,140);
			endY = _.getRandom(0,40);
			color = _.getRandomColor();
			//Define a straight line line = new Line(ctx,{
				x:0,
				y:0,
			 	startX:startX,
			 	startY:startY,
			 	endX:endX,
			 	endY:endY,
			 	strokeStyle:color
			})
			
			this.renderArr.push(line);
		}
	}

The effect is as follows:

Add page layout

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <title>verifiable</title>
  <style>
   #box{
		width:140px;
		height:40px;
		position:absolute;
		
	}
	#inputDiv{
		width:220px;
		position:absolute;
		margin:0 auto;
		left:0;
		top:30px;
		right:0;
		bottom:0;
	}
	#container{
		width:220px;
		height:60px;
		position:absolute;
		margin:0 auto;
		left:0;
		top:60px;
		right:0;
		bottom:0;
	}
	.refresh{
		position:absolute;
		left:140px;
	}
  </style>
</head>
 
<body>
	<div id='inputDiv'>
  	Verification code: <input size=10 id='codeInput'><img id='stateImg' style="vertical-align: middle;width:20px"></img>
  </div>
  <div id="container">
  	<div id='box'></div>
  	<a href="javascript:void 0" class="refresh" onclick="refresh()">Change one</a>
  </div>
</body>
	<script type="text/javascript" src='verifiable.js'></script>
  <script type="text/javascript">
 	var box = document.getElementById('box');
 	var stateImg = document.getElementById('stateImg');
 	var codeInput = document.getElementById('codeInput');
 	
	verifiable.init(box,codeInput,stateImg);
	
	//Change a picture function refresh(){
		verifiable.renderArr.length=0;
		verifiable.draw();
	}
  </script>
</html>

Add input box event

	//Input box event Verifiable.prototype.inputValid=function(input){
		var val = input.value;
		if(val.length<4) return ;
		
		if(this.code==val){
			console.log('suc');
			this.result(0);
		}else{
			this.result(1);
		}
	}

Add success and failure verification

//Processing results Verifiable.prototype.result=function(result){
		var codeInput = this.codeInput;
		var stateImg = this.stateImg;
		if(result==0){//Success stateImg.src="./images/suc.jpeg";
			codeInput.readOnly=true;
		}else {//Failure codeInput.readOnly=false;
			stateImg.src="./images/fail.jpeg";
			this.renderArr.length=0;
			this.draw();
		}
	}

Finish

Code Download

This concludes this article about the implementation example of JavaScript to implement dynamic verification code on the page. For more relevant JavaScript dynamic verification code content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Jsp method to generate page verification code [with code]
  • js implements simple verification code
  • js realizes the countdown effect of clicking to get the verification code
  • Three ways to implement JS verification code function
  • JS makes graphic verification code implementation code
  • js+canvas realizes the function of sliding puzzle verification code
  • js+html to make a simple verification code
  • JS verification code implementation code
  • js plug-in to implement image sliding verification code

<<:  Linux kernel device driver kernel time management notes

>>:  Detailed explanation of how to access MySQL database remotely through Workbench

Recommend

In-depth explanation of the global status of WeChat applet

Preface In WeChat applet, you can use globalData ...

Use Docker to build a Redis master-slave replication cluster

In a cluster with master-slave replication mode, ...

Example analysis of mysql stored procedure usage

This article describes the usage of MySQL stored ...

IDEA2020.1.2 Detailed tutorial on creating a web project and configuring Tomcat

This article is an integrated article on how to c...

idea uses docker plug-in to achieve one-click automated deployment

Table of contents environment: 1. Docker enables ...

Sitemesh tutorial - page decoration technology principles and applications

1. Basic Concepts 1. Sitemesh is a page decoratio...

Solution for Tomcat to place configuration files externally

question When we are developing normally, if we w...

Nginx Linux installation and deployment detailed tutorial

1. Introduction to Nginx Nginx is a web server th...

A simple method to modify the size of Nginx uploaded files

Original link: https://vien.tech/article/138 Pref...

JavaScript to achieve accordion effect

This article shares the specific code for JavaScr...

How to make your own native JavaScript router

Table of contents Preface Introduction JavaScript...

How to disable foreign key constraint checking in MySQL child tables

Prepare: Define a teacher table and a student tab...

Vue uses echart to customize labels and colors

This article example shares the specific code of ...