欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

删除特殊字符和限定用户输入长度的示例代码

程序员文章站 2024-02-29 20:16:10
复制代码 代码如下: /检查非法字符并检验字符长度 function checkspechar(obj, bytelength, title) { var value =...
复制代码 代码如下:

/检查非法字符并检验字符长度
function checkspechar(obj, bytelength, title) {
var value = document.getelementbyid(obj).value;
value = value.replace(/(^\s*)/g, "").replace(/(\s*$)/g, "");
var ret = (/[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']/.test(value));
var arr = ["@", "#", "$", "%", "^", "&", "*", "<", ">", "/", "\\", "\'", "'", ".", ":", "?", "[", "]", ";", "-", "、", "(", ")", "_", "\"", "~", "insert", "delete", "update", "select"];
value = value.tolowercase();
for (var i = 0; i < arr.length; i++) {
if (value.indexof(arr[i].tolowercase()) >= 0) {
ret = true;
}
}
if (ret == true) {
top.lsalert("内容中含非法字符,请重新输入!");
document.getelementbyid(obj).value = '';
return;
}
limitlength(value, bytelength, title, obj);
}
//验证输入字符长度
function limitlength(value, bytelength, title, attribute) {
value = value.replace(/\r/g, " ").replace(/\n/g, " "); //回车换行分别替换两个空格
var newvalue = value.replace(/[^\x00-\xff]/g, "***");
var length = newvalue.length;
//当填写的字节数小于设置的字节数
if (length * 1 <= bytelength * 1) {
return;
}
var limitdate = newvalue.substr(0, bytelength);
var count = 0;
var limitvalue = "";
for (var i = 0; i < limitdate.length; i++) {
var flat = limitdate.substr(i, 1);
if (flat == "*") {
count++;
}
}
var size = 0;
var istar = newvalue.substr(bytelength * 1 - 1, 1); //校验点是否为“×”
//if 基点是×;
if (count % 3 == 0) {
size = count / 3 + (bytelength * 1 - count);
limitvalue = value.substr(0, size);
}
else if (count % 3 == 1) {
size = (count - 1) / 3 + (bytelength * 1 - count);
limitvalue = value.substr(0, size);
}
else if (count % 3 == 2) {
size = (count - 2) / 3 + (bytelength * 1 - count);
limitvalue = value.substr(0, size);
}
//top.lsalert(title + "最大输入" + bytelength + "个字节!");
document.getelementbyid(attribute).value = limitvalue;
return;
}