天天看點

簡單生成微信小程式随機驗證碼

廢話不多說,直接上圖看效果

簡單生成微信小程式随機驗證碼

一、實作功能:

1、點選灰色底的驗證碼圖檔可以更換一張驗證碼

2、驗證輸入的驗證碼是否正确,并且輸入小大寫英文都可以、

二、核心代碼:

注意:我是用uni-app架構寫的,用原生寫的朋友自行修改一下寫法哈

html的代碼:

<template>
	<view>
		<form @submit="formSubmit">
    	<view class="down">
			<view>驗證碼:</view>
			<input class="down_input" name="code"></input>
			<text class="true_code" @tap="changeCode">{{code}}</text>
		</view>
		<button class="btn" form-type="submit">送出</button>
		</form>
	</view>
</template>
           

樣式的代碼:

<style>
	.down{
		width: 90%;
		margin: 0 auto;
		height: 50rpx;
		display: flex;
		flex-direction: row;
		margin-top: 20rpx;
	}
	.down_input{
		width: 110rpx;
		height: 50rpx;
		line-height: 50rpx;
		border:  1px solid #CCCCCC;
		border-radius: 6px;
		padding-left: 20rpx;
	}
	.btn{
		width: 300rpx;
		height: 70rpx;
		line-height: 70rpx;
		margin:0 auto;
		margin-top: 50rpx;
		color: white;
		background: #23EBB9;
		
	}
	.true_code{
		  width: 150rpx;
		  height: 52rpx;
		  line-height: 50rpx;
		  text-align: center;
		  font-family: Arial;
		  font-style: italic;
		  font-weight: bold;
		  border: 0;
		  letter-spacing: 3px;
		  font-size: 18px;
		  background-color: #ccc;
		  margin-left: 30rpx;
/* 		  padding: 10rpx; */
		  margin-right: 20rpx;
		  color: black;
	}
</style>
           

js的代碼:

<script>
	export default {
		data() {
			return {
				code:""
			}
		},
		methods: {
			formSubmit(e){
				if(e.detail.value.code=""){
					uni.showToast({
						title:"請輸入驗證碼",
						icon:"none"
					})
				}
                //将輸入的驗證碼和生成的驗證碼都轉為全大寫字母,然後再比較是否相等
                else if(e.detail.value.code.toUpperCase()==this.code.toUpperCase()){
					console.log("驗證碼輸入正确")
				}
			},
			changeCode(e){
				    var code;
				    //首先預設code為空字元串
				    code = '';
				    //設定長度,這裡看需求
				    var codeLength = 4;
				    //設定随機字元
				    var random = new Array(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');
				    //循環codeLength 我設定的4就是循環4次
				    for (var i = 0; i < codeLength; i++) {
				      //設定随機數範圍,這設定為0 ~ 62(10+26+26)
					  var index = Math.floor(Math.random() * 62);
				      //字元串拼接 将每次随機的字元 進行拼接
				      code += random[index];
				    }
					this.code=code;
			}
		},
		onLoad() {
			this.changeCode();
		}
	}
</script>