测试函数
function validateDate(inputField, helpText) {
// First see if the input value contains data
if (!validateNonEmpty(inputField, helpText))
return false;
// Then see if the input value is a date
return validateRegEx(/^\d{2}\/\d{2}\/\d{2,4}$/,
inputField.value, helpText,
"Please enter a date (for example, 01/14/1975).");
}
正则表达式验证函数
function validateRegEx(regex, input, helpText, helpMessage) {
// See if the input data validates OK
if (!regex.test(input)) { //测试非法数据
// The data is invalid, so set the help message and return false
if (helpText != null)
helpText.innerHTML = helpMessage;
return false;
}
else {
// The data is OK, so clear the help message and return true
if (helpText != null)
helpText.innerHTML = "";
return true;
}
}
regex:正则表达式
input:输入数据
helpText:提示信息的对象指针
helpMessage:提示信息
逻辑:首先确认是否为空值,如果为空则提示用户输入数据,如果不为空,则通过回调函数调用正则测试函数,执行以下逻辑:
如果不满足regex.test,且helpText的指针正确,则提示用户,信息输入错误。用户重新输入后,出发onblur函数,重新验证,直到输入的数据符合条件。
正则表达式一些基本用法
元字符:
·:匹配任何字符,换行除外
\d:匹配数字
\w:匹配字母
\s:匹配空格
^:起始符,以XX开始
$:结束符,以XX结束
限定符
*:0或多次
+:1或多次
?:0或1次
{n}:n次
():可以用来集合字符
正则表达式直接可以用变量进行声明。
var regex = /^\d{5}/ // 用两个//里面写字符来进行设置
正则表达式常用函数:
正则.test(字符串) : 判断字符串是否满足正则表达式,返回true or false
字符串.search(正则):在字符串中寻找满足正则表达式的内容,如果找到,则返回找到该字符的位置(下标),搜索失败则返回-1
字符串.match(正则):搜索满足正则的内容,返回该内容,返回的是数组,另外只返回第一个找到的数据。
字符串.replace(正则,新的字符串/回调函数):找到正则相关内容,并以新的内容替换他。