I'm trying to validate my file name and file extension using regular expression. My file name should only contain these characters:'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,_,.,@,-,(,), ' and my extension only should accept .txt files. My current function is pretty complicated and requires nested looping what I don't like. So I would like to check all of this in one single expression. Here is my current code:
fileName = 'My Document.txt'
fileExt = fileName.substr(fileName.length-4)
validCharList='A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,_,.,@,-,(,), ';
err = false;
letterOk = false;
for(i=0;i<fileName.length;i++){
letterOk = false;
for(b=0;b<validCharList.length;b++){
if(fileName.charAt(i) == validCharList.charAt(b)){
letterOk = true;
break;
}
}
if(letterOk == false){
alert('file name has an invalid character.');
return false;
break;
}
}
if(fileExt != '.txt' && fileExt != '.TXT'){
alert(Your document does not have a proper file extension.)
return false;
}
If anyone can help with this please let me know. Thanks!