最近在项目中用到RegularExpressionValidator,需要对上传的文件的扩展名进行限制。
可以把文件的扩展名写成大写或者小写字母都没有问题,操作系统都可以识别。例如把.xls,写成.XLS或者Xls等。所有就需要正则匹配的时候,忽略大小写字符。
RegularExpressionValidator本身并不支持大小写,这就需要我们对其前台js验证进行改写。
aspx页面中RegularExpressionValidator控件的ValidationExpression属性的写法为加"(?i)”前缀。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<
asp:RegularExpressionValidator Display
=
"
none
"
ID
=
"
fileupLoadValidator
"
runat
=
"
server
"
ValidationGroup = " Import " ErrorMessage = " 只允许上传csv或者xls文件! " ValidationExpression = " (?i)^.+\.((csv)|(xls))$ "
ControlToValidate = " fuCSV " ></ asp:RegularExpressionValidator >
ValidationGroup = " Import " ErrorMessage = " 只允许上传csv或者xls文件! " ValidationExpression = " (?i)^.+\.((csv)|(xls))$ "
ControlToValidate = " fuCSV " ></ asp:RegularExpressionValidator >
这样子后台验证可以通过了,可以前台js不认识这样写的正则表达式,这就是我们需要改造的。代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<
script type
=
"
text/javascript
"
>
function RegularExpressionValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0 )
return true ;
var rx = null ;
if (val.validationexpression.indexOf( " (?i) " ) >= 0 ) {
rx = new RegExp(val.validationexpression.replace( " (?i) " , "" ), " i " );
} else {
rx = new RegExp(val.validationexpression);
}
var matches = rx.exec(value);
return (matches != null && value == matches[ 0 ]);
}
</ script >
function RegularExpressionValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
if (ValidatorTrim(value).length == 0 )
return true ;
var rx = null ;
if (val.validationexpression.indexOf( " (?i) " ) >= 0 ) {
rx = new RegExp(val.validationexpression.replace( " (?i) " , "" ), " i " );
} else {
rx = new RegExp(val.validationexpression);
}
var matches = rx.exec(value);
return (matches != null && value == matches[ 0 ]);
}
</ script >
这段代码需要放在form的底部,
不要放到了form外面,body的底部。
经过这样的改造,RegularExpressionValidator的验证就可以忽略大小写了。