本文實(shí)例講述了javascript簡單判斷輸入內(nèi)容是否合法的方法。分享給大家供大家參考,具體如下:
關(guān)于檢測用戶輸入的內(nèi)容是否有非法的字符檢測實(shí)現(xiàn)思路
1、定義合法的字符串(源字符串)
2、獲取用戶輸入的內(nèi)容
3、循環(huán)的取出用戶輸入的每一個(gè)字符,去源字符串中查找
1)、查找到了,返回字符串查找的位置
2)、沒有找到返回-1,我們正好利用-1檢測用戶輸入的內(nèi)容是否合法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML1.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="檢驗(yàn)是否可用"/></form></body></html> 


















