时间:2021-07-01 10:21:17 帮助过:9人阅读
代码:
var fv =
{
lang: "zh-cn", //错误提示语言
inValidedStr: "=", //初始随意复制,使其长度不为0
mail: function(elementID) //验证邮件地址合法,elementID为input文本输入框的ID
{
if (elementID == null) { return true; }
else
{
var reg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
if (reg.test(document.getElementById(elementID).value))
{
fv.inValidedStr = fv.inValidedStr.replace(/mail/g, "");
fv.inValidedStr = fv.inValidedStr.replace("=", "");
validMsg(fv.lang, "mail", "mailInfo");
}
else
{
fv.inValidedStr = fv.inValidedStr + "mail";
errorMsg(fv.lang, "mail", "mailInfo");
}
}
},
username: function(elementID) //验证用户名合法 字母数字下划线,长度为6-20
{
if (elementID == null) { return true; }
else
{
var reg = /^[a-zA-Z0-9_]{5,19}$/;
if (reg.test(document.getElementById(elementID).value))
{
fv.inValidedStr = fv.inValidedStr.replace(/username/g, "");
fv.inValidedStr = fv.inValidedStr.replace("=", "");
validMsg(fv.lang, "username", "usernameInfo");
}
else
{
fv.inValidedStr = fv.inValidedStr + "username";
errorMsg(fv.lang, "username", "usernameInfo");
}
}
},
//....可以加其他验证
isValid: function() { return (fv.inValidedStr.length == 0); }
};
//验证成功时的信息 elementID 为信息提示的html单元的id
function validMsg(lang, valueType, elementID)
{
var msgInfo = "";
var isCn = lang == "zh-cn";
switch (valueType)
{
case "mail":
msgInfo = isCn ? " √ 地址正确" : " √ the mail address is valided";
break;
case "username":
msgInfo = isCn ? " √ 成功" : " √ The account valided ";
break;
case "password":
msgInfo = isCn ? " √ 成功" : " √ Valided format!";
break;
//.....对应增加其他情况
default:
break;
}
document.getElementById(elementID).innerHTML = msgInfo;
document.getElementById(elementID).style.color = "green";
}
//验证失败时的信息
function errorMsg(lang, valueType, elementID)
{
var msgInfo = "";
var isCn = lang == "zh-cn";
switch (valueType)
{
case "mail":
msgInfo = isCn ? " × 请输入正确的邮件地址" : " × The e-mail format is error,plz input right format .eg. abc@def.com.";
break;
case "username":
msgInfo = isCn ? " × 长度6-20个字符,只能为数字,字母,下划线组成" : " × The account just ";
break;
case "password":
msgInfo = isCn ? " × 密码为……" : " × inValided format!";
break;
//....对应增加其他情况
default:
break;
}
document.getElementById(elementID).innerHTML = msgInfo;
document.getElementById(elementID).style.color = "red";
}