用户名不能为空
2016-05-14 13:56
447 查看
在表单中经常些必填项目,如果用户没有输入则不允许提交表单。例如在注册用户时,必须填写用户名才能提交注册信息。验证用户是否输入时,通常需要先过滤再验证(如果用户输入的都是空格就相当于没有输入)。
我们通过使用正则表达式匹配空格
调用string的replace方法清除空格
创建一个函数:
具体代码如下:
HTML:
css:
javascript:
demo演示地址:点击这里
我们通过使用正则表达式匹配空格
var regex = /\s+/g;
调用string的replace方法清除空格
string.replace(regex,'');
创建一个函数:
function regexEmpty(obj){ obj.value = obj.value.replace(regex,''); }
具体代码如下:
HTML:
< div class= "main"> < input id= "userName" type= "text" placeholder= "请输入用户名" > < input id= "rule" type= "button" value= "验证"> </ div>
css:
html,body ,div, input{margin :0; padding:0 ;} .main{width :400px ;height: auto;padding :0 15px; text-align:center; } .main input{width :100% ;height: 35px; border:none ;margin-top: 20px; border-radius:5 px;} input[type ="text"] {text-align: left;padding-left :15px ;box-sizing: border-box;border :1px solid green; } input[type ="button"] {width: 50%; background:green; }
javascript:
var userName = document.getElementById('userName' ), rule = document.getElementById( 'rule'), deleteEmpty = null, regex = /\s+/g; deleteEmpty = function (obj){ obj.value = obj.value.replace(regex,'' ); if(! obj.value){ alert( '用户名不能为空' ); } else{ alert('pass'); } } rule. onclick = function (){ deleteEmpty(userName); };
demo演示地址:点击这里
相关文章推荐
- 学习进度条
- 将前缀和后缀相同的文件移动到同一个目录的算法设计及C代码实现
- getsockopt 和 setsockopt讲解
- Qt removeDatabase正确方法
- WAJUEJI which home strong! nyoj 1100
- SQL关联查询总结
- android SeekBar设置背景无法被填充满的bug
- C补习
- 【排序】基数排序
- Time类中的运算符重载
- 关于django服务器重启端口占用解决方案
- java中的PO/VO/DAO/BO/POJO简单介绍
- java实现静态图片剪切缩放功能【工具类】
- 观察者模式
- 倒排句子的单词
- Json解析详细教程
- ClassNotFoundException: org.apache.ws.commons.schema.resolver.URIResolver
- 第三节,入门知识和windows系统安装python环境
- Spring+mybatis分库分表
- 表单新增元素与属性