javascriptregexvalidation

How to validate file name and file extension from single Regex?


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!


Solution

  • Something like this?

    return /^[a-z0-9_.@()-]+\.txt$/i.test(fileName);
    

    If you want two separate checks, are you indicate in comments, you might do something like this:

    var validFilename = /^[a-z0-9_.@()-]+\.[^.]+$/i.test(fileName);
    var validExtension = /\.txt$/i.test(fileName);
    

    The first expression tests everything up until the last period, and verifies that there is at least one non-period character after the last period, comprising the extension.

    If you don't want to bother with the definition of what is a filename, you may instead invert the test, and explicitly check for the presence of invalid characters (here I'm testing the entire string again, so validFilename will be false even if you have invalid characters only in the extension - one way around that would be to validate extension before filename)

    var validFilename = !/[^a-z0-9_.@()-]/i.test(fileName);