先引入库

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>

css

  1. form{
  2. display: grid;
  3. width: 20em;
  4. gap:1em;
  5. border:1px solid gray;
  6. padding: 1em;
  7. }

html

  1. <form action="check.php">
  2. 账号:<input type="text" name="username" />
  3. 密码:<input type="password" name="password" />
  4. <button>登录</button>
  5. </form>

js

  1. // 禁用表单的默认提交行为
  2. $("form").submit(ev=>ev.preventDefault());
  3. //document.querySelector("form").onsubmit=ev=>ev.preventDefault();//原生写法
  4. // 验证用户名是否为空,为空则提示不能为空,不为空验证用户名是否存在,存在则提示已存在,不存在提示可以注册
  5. const user=$("input[name='username']");
  6. //失去焦点时进行验证
  7. user.blur(function(){
  8. //不能使用箭头函数,因为箭头函数没有自己的this,它的this来自上上文
  9. // 提示信息
  10. let tips="";
  11. // 用户列表(用于测试)
  12. const users=['admin','web','jy'];
  13. //进行非空验证
  14. if($(this).val().length===0){
  15. //值得长度为0进行提示
  16. tips="用户名不能为空";
  17. $(this).focus();//激活输入框
  18. } else if(users.indexOf($(this).val())===-1){
  19. //返回-1则表示此值在用户列表中没有
  20. tips="用户名不存在,请注册"+"<button>注册</button>";
  21. }else{
  22. tips="<i style='color:green;'>用户名正确</i>";
  23. }
  24. //防止提示信息重复插入页面(判断其下一个元素的名字时不是SPAN)
  25. if($(this).next()[0].tagName!=="SPAN"){
  26. $("<span></span>").html(tips).css("color","red").insertAfter($(this));
  27. }
  28. })
  29. //用户修改文本的输入时,将提示信息清空
  30. user.on("input",function(){
  31. $(this).next("span").remove();
  32. })

更多相关文章

  1. 前端插件:form.js和validate.js的简单入门使用
  2. tp6 多文件上传
  3. 时间同步、双因子安全验证及自动化安装实现过程
  4. 上传自己的镜像被拒绝denied: requested access to the resource
  5. 员工管理系统完整版(登录验证功能+网址过滤白名单)
  6. Python-web验证码的实现
  7. ThinkPHP的使用笔记:验证码的使用和session的使用
  8. PHP表单验证实例DOME分享
  9. leetcode331 验证二叉树的前序序列化 golang

随机推荐

  1. 【机器学习算法-python实现】最大似然估
  2. 毕业设计-基于深度神经网络的语音关键词
  3. FieldErro:无法将关键字'date_added'解析
  4. Python 25 Django跨域请求
  5. pytorch中tensor数据和numpy数据转换中注
  6. Python机器学习之Logistic回归
  7. 【懒懒的Tensorflow学习笔记三之搭建简单
  8. 求助!为什么我连python的hello word都写不
  9. 【爬虫初探】新浪微博搜索爬虫实现
  10. KNN(K近邻分类器)Python3实现