jQuery 手机号和验证码验证代码示例
使用jQuery实现手机号和验证码验证
手机号验证
$('#phone').blur(function() {
if ($.trim($(this).val()) === '') {
$('#phone_msg').html('手机号不能为空');
} else {
var reg = /^1[3456789]\d{9}$/;
if (!reg.test($(this).val())) {
$('#phone_msg').html('手机号格式错误!');
} else {
$('#phone_msg').html('√').css('color', 'green');
}
}
});
随机生成验证码
function generateCode() {
var code = '';
for (var i = 0; i < 4; i++) {
var randomNum = Math.floor(Math.random() * 10);
code += randomNum;
}
return code;
}
$('#code').val(generateCode());
验证码验证
$('#code').blur(function() {
if ($.trim($(this).val()) === '') {
$('#code_msg').html('验证码不能为空');
} else {
if ($(this).val() !== $('#code').val()) {
$('#code_msg').html('验证码错误!');
} else {
$('#code_msg').html('√').css('color', 'green');
}
}
});
HTML 代码
<div>
<label for="code">验证码:</label>
<input type="text" id="code" name="code">
<span id="code_msg"></span>
</div>
说明:
- 使用
$.trim()函数去除字符串两端的空格,确保验证的准确性。 - 使用正则表达式
/^1[3456789]\d{9}$/验证手机号格式。 generateCode()函数生成一个4位随机数作为验证码。- 验证时,将用户输入的验证码与生成的验证码进行比较。
- 使用
css()方法设置验证结果的样式。
原文地址: https://www.cveoy.top/t/topic/njfW 著作权归作者所有。请勿转载和采集!