首页 > 代码库 > js正则表达式验证

js正则表达式验证

有时候会要验证自己写的正则表达式是否正确

所以写了这个小东西:

技术分享

demo:js正则表达式验证

 

html:

1 <h3>绿色表示匹配,红色表示不匹配</h3>2 <label>请在下框填入正则表达式</label><br />3 4 <textarea id="regexp"></textarea><br />5 6 <label>请在下框填需要验证的式子</label><br />7 8 <textarea id="needtest"></textarea>

css:

1 #regexp,#needtest { height:100px; width:300px; resize:none; font-weight:bold;}

javascript:

 1 window.onload = function(){ 2      3      4      5     document.getElementById(‘needtest‘).onkeyup = function(){ 6         var ret = document.getElementById(‘regexp‘).value; 7         ret = ‘^‘ + ret + ‘$‘; 8         var re = new RegExp(ret) 9         10         if(re.test(document.getElementById(‘needtest‘).value)){11             12             document.getElementById(‘needtest‘).style.color = ‘green‘;13         }else{14             document.getElementById(‘needtest‘).style.color = ‘red‘;15         }16     }17     18     document.getElementById(‘regexp‘).onkeyup = function(){19         var ret = document.getElementById(‘regexp‘).value;20         ret = ‘^‘ + ret + ‘$‘;21         var re = new RegExp(ret)22         23         if(re.test(document.getElementById(‘needtest‘).value)){24             25             document.getElementById(‘needtest‘).style.color = ‘green‘;26         }else{27             document.getElementById(‘needtest‘).style.color = ‘red‘;28         }29     }30     31 }

 

js正则表达式验证