<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div>请输入邮箱:<input id="email" type="text"><span id="emailInfo"></span></div> <div>请输入密码:<input id="pwd" type="password"><span id="pwdInfo"></span></div> <button type="button">提交</button> </body> <script src="jquery.min.js"></script> <script> $(function(){
//对获取数据进行简单验证(这不是重点) var em = /\w+@\w+\.\w+/;
//当失去焦点时触发事件 $('#email').on('blur', function () { if(em.test($(this).val())){ $('#emailInfo').html('正确').css('color','green'); }else{ $('#emailInfo').html('错误').css('color','red');
//输入错误时不能脱离焦点 $(this).focus(); } }); $('#pwd').on('blur', function () { var p = $(this).val(); if(p.length <= 16 && p.length >= 6){ $('#pwdInfo').html('正确').css('color','green'); }else{ $('#pwdInfo').html('错误').css('color','red'); $(this).focus(); } }); $('button').on('click',function(){ $('#pwdInfo').html(''); $('#emailInfo').html('');
//通过ajax与后端进行交互,在规定好的规则内返回既定的值 $.get('server.php',{'email':$('#email').val(),'pwd':$('#pwd').val()},function(e){ if(e == 0){ $('#emailInfo').html('请输入正确的邮箱').css('color','red'); $('#email').focus(); } if(e == 1){ $('#pwdInfo').html('请输入正确的密码').css('color','red'); $('#pwd').focus(); } if(e == 2){ alert('成功'); } }) }) }) </script> </html>
前端jquery即时验证问题
最新推荐文章于 2024-08-05 21:28:12 发布