<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><title> RegExp对象</title><script>/*function validation(obj){//1.得到文本框的值//var name = document.getElementById("username").value;var name = obj.value;//2.定义一个正则表达式var regexp = new RegExp("[a-zA-Z]{6,10}");//3.匹配var bvalue = regexp.test(name);//4.判断if(bvalue){alert("用户名格式正确");}else{alert("用户名格式错误,只能6-10位字母组成");}}*///调用函数规则一般:事件名="函数名()"//onclick:点击//onblur:失去焦点 οnblur="validation(this)" this代表当前的标签//onfocus:得到焦点//即时的消息提示 function validationsw(obj){//1.得到文本框的值//var name = document.getElementById("username").value;var name = obj.value;//2.定义一个正则表达式var regexp = new RegExp("^[a-zA-Z]{6,10}$");//3.匹配var bvalue = regexp.test(name);//根据id找到divvar errorsw = document.getElementById("errorMsg");//4.判断 //innerHTML代表的是<div></div>中间的文本,而且能识别html标签//innerText:代表的是<div></div>中间的文本,但不能识能html标签if(bvalue){errorsw.innerHTML="<font color='red'>用户名格式正确</font>";}else{errorsw.innerHTML="<font color='red'>用户名格式错误,只能6-10位字母组成</font>";}}function clearText(objhsw){var hswvalue = objhsw.value;if(hswvalue == "只能6-10位字母组成"){objhsw.value="";}}function changeChar(obj){var source = obj.value;if(source!="只能是6-10位的字母组成"){var regExp = new RegExp("^[a-zA-Z]{6,10}$");flag = regExp.test(source);}var errorsw = document.getElementById("errorMsg2");if(!flag){errorsw.innerHTML = "<font color='red'>只能是6-10位的字母组成</font>";}else{errorsw.innerHTML = "<font color='green'>ok</font>";}}</script></head><body><input type="text" value="只能6-10位字母组成" id="username" name="username" οnfοcus="clearText(this)" οnblur="validationsw(this)" /><div id="errorMsg" style="display:inline;"></div><hr size="3cm" color="blue"/><input id="source" type="text" value="只能是6-10位的字母组成" size="30" οnchange="changeChar(this)" /><div id="errorMsg2" style="display:inline;"></div></body>
</html>
转载于:https://www.cnblogs.com/thankyou/p/4352069.html