Home > Web Front-end > JS Tutorial > body text

javascript简单判断输入内容是否合法的方法_javascript技巧

WBOY
Release: 2016-05-19 10:42:40
Original
2056 people have browsed it

本文实例讲述了javascript简单判断输入内容是否合法的方法。分享给大家供大家参考,具体如下:

关于检测用户输入的内容是否有非法的字符检测实现思路

1、定义合法的字符串(源字符串)
2、获取用户输入的内容
3、循环的取出用户输入的每一个字符,去源字符串中查找
  1)、查找到了,返回字符串查找的位置
  2)、没有找到返回-1,我们正好利用-1检测用户输入的内容是否合法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>用户名是否可用</title>
<script type="text/JavaScript"language="javascript">
   function username(){
     var regex=/[a-zA-Z0-9_]*/;
     var username =document.getElementById('text').value;
     vara=regex.exec(username);
     if(a!=""){
       alert('用户名可用!');
     }else{
       alert('有非法字符');
     }
   }
</script>
</head>
<body>
<form>
   用户名:<input type="text"id="text" />
   <inputtype="button" onClick="username();" value="检验是否可用"/>
</form>
</body>
</html>

Copy after login

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结

希望本文所述对大家JavaScript程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!