js表单验证

120 阅读1分钟
  • let form = document.getElementById('form') | form.onsubmit = function (){

  • 字符串非空验证.getElementById('usernam

  • if(username.trim() == '

  • let username = document'){e').value;

  • 字符串的trim()方法可以去除左右的空格

  • alert('用户名不能为空')

  • 阻止表单提交的默认事件

  • return false;

  • }

  • 继续执行默认事件

  • return true;

  • 字符串查找验证

  • ar str="this is JavaScript";

  • str.indexOf('is')

  • 2

  • var str="this is JavaScript";

  • 从下标是3的位置开始寻找 找的到返回对应的下标

  • 找不到返回 -1

  • str.indexOf('is',3)

  • 5

  • str.indexOf('is',6)

  • -1

  • let form = document.getElementById('form')

  • form.onsubmit = function (){

  • let pwd = document.getElementById('pwd').value;

  • 先校验是否为空 再校验里面的内容

  • 排除异常

  • if(pwd.trim() == ''){

  • alert('密码不能为空')

  • return false;

  • }

  • 邮箱的长度验证

  • if(pwd.length<6){

  • alert('密码长度不能小于6个字符串')

  • return false;

  • }

  • let rpwd = document.getElementById('rpwd').value;

  • | if(pwd != rpwd){alert('两次密码不一致')

  • return false

  • }

  • let user = document.getElementById('user').value;

  • for(let i=0;i<user.length;i++){

  • if( isNaN(user[i])==false ){

  • alert('用户名不能输入数字')

  • return false

  • }

  • }

  • return true;