JS实现选择不同select标签option值的验证

js实现不同select标签option值的验证

功能描述:

选择中文时,匹配中文的正则表达式,选择英文选项是匹配英文的表达式,并且有对应的提示信息。

html代码片段:

<select id="word_type" name="S1">
            <option value="0">中文</option>
            <option value="1">英文</option>
 </select>
        <input name="" id="searchbox" type="text" />
        <button onclick="search_word()">搜索</button>

JS代码片段:

<script>
         function trimStr(str){
             return str.replace(/(^\s*)|(\s*$)/g,"");//去掉空格
         }
         function search_word(){
             var sword = document.getElementById("searchbox").value;//获取下拉框所选值
             if(trimStr(sword) == ""){
                 alert( "输入不能为空!");
             }
             else{
                  if( document.getElementById("word_type").value == '0') {
                     var chinese=/^[\u4e00-\u9fa5]+$/;//匹配中文,需要在正则表达式前加上转义符
                     if (!chinese.exec(sword))
                     {
                         alert( "输入错误,请输入中文!");
                     }
                     else
	                   {
	                       return ture;
	                   }
                 }
                 else{
                     var english=/^[a-zA-Z]+$/;//匹配英文,需要在正则表达式前加上转义符
                     if (!english.exec(sword))
                     {
                         alert("输入错误,请输入英文!");
                     }
                     else
	                   {
	                       return ture;
	                   }
                 } 
             }
         }
</script>
posted @ 2015-09-26 16:43  纸鸢&红豆·绿豆  阅读(978)  评论(0编辑  收藏  举报