Solved

does javascript have a wildcard

Posted on 2011-03-14
17
604 Views
Last Modified: 2012-05-11
Hi,

I have a javascript function that does a file vaildation on a input file who's name is generated dynamically. (based on a button click)  "userfile_p#qprojects.req_part_id#_n"

Is there a wildcard character that I can use so that i capture all the characters after the "n" at the end?  These will be numbers that increment by 1 ie
userfile_p#qprojects.req_part_id#_n1
userfile_p#qprojects.req_part_id#_n2 etc.

Thanks for the help


<script type="text/javascript" language="JavaScript">
function ExtensionsOkay() {
var extension = new Array();
var fieldvalue = document.upload_form.userfile_p#qprojects.req_part_id#_n.value;

extension[0] = ".pdf";

var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));
for(var i = 0; i < extension.length; i++) {
	if(thisext == extension[i]) { return true; }
	}
alert("Your upload form contains an unapproved file name.");
return false;
}
</script>

Open in new window

0
Comment
Question by:smfmetro10
  • 7
  • 6
  • 2
  • +2
17 Comments
 
LVL 40

Expert Comment

by:gurvinder372
ID: 35131350
yes, you can use regular expression

var str = "userfile_p#qprojects.req_part_id#_n1";
var myArray = str.match(/userfile_p#qprojects.req_part_id#_n[0-9]/g)

if ( myArray != null) {
for ( j = 0; j < myArray.length; j++ ) {
var result = "myArray[" + j + "] = " + myArray[j];
}
}
0
 
LVL 82

Expert Comment

by:leakim971
ID: 35131464
no wildcard. jquery have something like start by, contains and so on
http://api.jquery.com/contains-selector/
http://api.jquery.com/attribute-starts-with-selector/

but not javascript...

you may use something like :
	for(var n=1;n<=5;n++) {
		var field = document.getElementsByName("req_part_id#_" + n)[0];
		// do something with each element
	}

Open in new window


test page :
<html>
<head>
<script>
window.onload = function() {
	for(var n=1;n<=5;n++) {
		var field = document.getElementsByName("req_part_id#_" + n)[0];
		alert( field.value )
	}
}
</script>
</head>
<body>
<input type="text" value="ABCD" name="req_part_id#_1" />
<input type="text" value="EFGH" name="req_part_id#_2" />
<input type="text" value="IJKL" name="req_part_id#_3" />
<input type="text" value="MNOP" name="req_part_id#_4" />
<input type="text" value="QRST" name="req_part_id#_5" />
</body><html>

Open in new window

0
 

Author Comment

by:smfmetro10
ID: 35131613
Thanks for the reply.
I get a "result is undefined error"  Can you take a look and see what I'm doing wrong?

Thanks


<script type="text/javascript" language="JavaScript"><!--
function ExtensionsOkay() {
var extension = new Array();

var str = "userfile_p#qprojects.req_part_id#_n1.value";
var myArray = str.match(/userfile_p#qprojects.req_part_id#_n[0-9]/g.value)

if ( myArray != null) {
for ( j = 0; j < myArray.length; j++ ) {
var result = "myArray[" + j + "] = " + myArray[j];
}
}

extension[0] = ".pdf";

var thisext = result.substr(fieldvalue.lastIndexOf('.'));
for(var i = 0; i < extension.length; j++) {
	if(thisext == extension[j]) { return true; }
	}
alert("Your upload form contains an unapproved file name.");
return false;
}
</script>

Open in new window

0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 51

Expert Comment

by:HainKurt
ID: 35131805
use this

var n=fieldvalue.substr(fieldvalue.lastIndexOf('#_n')+3);
n = n.substr(0, n.indexOf("."));



<script type="text/javascript" language="JavaScript">
function ExtensionsOkay(fieldvalue) {
var extension = new Array();
//var fieldvalue = "document.upload_form.userfile_p#qprojects.req_part_id#_n".value;

extension[0] = ".pdf";

var n=fieldvalue.substr(fieldvalue.lastIndexOf('#_n')+3);
n = n.substr(0, n.indexOf("."));
alert ("n = " + n);
var thisext = fieldvalue.substr(fieldvalue.lastIndexOf('.'));

for(var i = 0; i < extension.length; i++) {
	if(thisext == extension[i]) { return true; }
	}
alert("Your upload form contains an unapproved file name.");
return false;
}
alert(ExtensionsOkay("userfile_p#qprojects.req_part_id#_n123.pdf"));
</script>

Open in new window

0
 
LVL 1

Expert Comment

by:JerseyFoo
ID: 35132357
Important, you should read;

Do not check filetypes simply by filename.  I hacked a website and gained complete control of the server this way.  Of course you probably have holes everywhere anyway.

Also here's some code...
function validateFileName(fileName){
   var extensions = ['.pdf', '.wtf'];
   
   var match = fileName.match(/\.[a-z0-9]{1,4}/ig);
   var i = match.length;
   
   while ( i > 0 && match[--i] in extensions ){}

   return !i;
}

// For testing
var fn;
alert( (validateFileName(fn = 'phallus.php.pdf') ? 'Approved' : 'Fail')+'; '+fn );

alert( (validateFileName(fn = 'phallus.pdf.php') ? 'Approved' : 'Fail')+'; '+fn );

alert( (validateFileName(fn = 'phallus.pdf') ? 'Approved' : 'Fail')+'; '+fn );

Open in new window

0
 

Author Comment

by:smfmetro10
ID: 35132469
@HainKurt: why do you put "+3"?

These files are being dynamically generated based on a button click so there could be any number of files being uploaded

Thanks
0
 
LVL 1

Expert Comment

by:JerseyFoo
ID: 35132539
smfmetro, if it isn't obvious -- my code has that 'wildcard' you're looking for as well as being half the length and checking for multiple extensions.
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 35132544
3 is for "#n_", not the number of digits after this. It says, find index of "#n_" and add 3 to this index so it will point the first digit of number after that...

so it may be

xxxxxxxxxx#n_1.pdf
xxxxxxxxxx#n_123.pdf
xxxxxxxxxx#n_1234976.pdf

the script will work fine...

0
 

Author Comment

by:smfmetro10
ID: 35132800
on a form dump the file names are
xxxx#n_1.pdf
xxxxx#n_2.pdf
xxxx#n_3.pdf etc

0
 

Author Comment

by:smfmetro10
ID: 35132876
@JerseyFoo: where would you put the alerts for people uploading something other than a pdf?

Javascript/jquery newbie

thanks
0
 
LVL 1

Expert Comment

by:JerseyFoo
ID: 35132939
It has it in the code actually.  But if you need longform..

if ( !validateFileName('filename.pdf') ){
    alert('You're doing it wrong.');
}

Where 'filename.pdf' may be replaced with whichever variable or method you're using.
0
 

Author Comment

by:smfmetro10
ID: 35133056
hmmm.. I'm completelyl lost now. Im getting multiple errors.

All i want to do is check to see if a particular file (that is dynamically named) has an extension of .pdf, jpg,gif,bmp,mp4, flv.

Then name of the file (that doesnt change) is: userfile_p#qprojects.req_part_id#_n.

Then the amount of times a user clicks the "Add file" button determines what integer is placed after the "n"  ie
userfile_p#qprojects.req_part_id#_n1
userfile_p#qprojects.req_part_id#_n2
userfile_p#qprojects.req_part_id#_n3


0
 
LVL 1

Expert Comment

by:JerseyFoo
ID: 35133520
If you'd just like to grab the number, use this;
var str = 'userfile_p#qprojects.req_part_id#_n1';
var regex = /_n([0-9]+)/;
var match = regex.exec(str);
var number = match[1];

alert( match[1] );

Open in new window


It's called regex, a language for string parsing -- rather difficult to learn but easy to use.  And javascript has native support for it with /regexGoesHere/;

/_n([0-9]+)/

It  grabs a sequence of digits (0,1,2,3,4,5,6,7,8,9) after "_n" and stores it to match[1].  match[0] is the entire match which includes _n.

Reference if you care to learn;
   [ ] matches any of the characters enclosed
   0-9 is a shortcut for 0123456789 inside the [ ]
   + means 1 or more characters in a row
   ( ) stores the inner match to the first variable; match[1]
0
 

Author Comment

by:smfmetro10
ID: 35133698
Thank you so much for taking the time to explain things to me!

So... Why doesnt this work?


<script language="javascript">
function ExtensionsOkay() {
var extension = new Array();
var str = document.upload_form.userfile_p#qprojects.req_part_id#_n.value;
var regex = /_n([0-9]+)/;
var match = regex.exec(str);

extension[0] = ".pdf";
var thisext = match.substr(match.lastIndexOf('.'));
for(var i = 0; i < extension.length; i++) {
	if(thisext == extension[i]) { return true; }
	}
alert("Your upload form contains an unapproved file name.");
return false;
}
</script>

Open in new window

0
 
LVL 1

Accepted Solution

by:
JerseyFoo earned 500 total points
ID: 35134642
You can't stick codes together and expect them to get to know each other.

I'm going to assume document.upload_form.userfile_p#qprojects.req_part_id#_n.value is a property and not a string.

 
/* this will iterate through the file elements */
var n = 1;
var fileName;
while ( document.upload_form.userfile_p#qprojects['req_part_id#_n'+n] ){
    fileName = document.upload_form.userfile_p#qprojects['req_part_id#_n'+n].value;
    // process fileName
    n++;
}

Open in new window


Then just make use of my function here which returns true if all the extensions are valid, and false if they are not.
function validateFileName(fileName){
   var extensions = ['.pdf', '.wtf'];
   
   var match = fileName.match(/\.[a-z0-9]{1,4}/ig);
   var i = match.length;
   
   while ( i > 0 && match[--i] in extensions ){}

   return !i;
}

Open in new window


Like so...
if ( !validateFileName(fileName) ){
    alert('Your upload form contains an unapproved file name.');
    // exit script
}

Open in new window


Otherwise, please make use of the id attribute ( <input id="file_n1" ) and use document.getElementById to fetch it as I'm not sure what you're doing with all those #'s.
0
 

Author Comment

by:smfmetro10
ID: 35140217
Thanks for all the help.

If I understand correctly (and i probably don't) I have assembled the code like this:

However, when the page loads  I get a "docucment.upload_form is undefined" error
- the name of the form is "upload_form"

and upon adding a file upload and hitting submit I get a "validateFilename is undefined" error

Ps. The #'s are from coldfusion. so somethin like userfile_p#qprojects.req_part_id# is looking in the database for the req_part_id column and returning a number. So if you look at the source code it would be something like "userfile_p2101_n1" then userfile_p2101_n2....

Thanks again for taking the time to help me with this
<script language="javascript">
var n = 1;
var fileName;
while ( document.upload_form.userfile_p#qprojects.req_part_id#_n+n ){
    fileName = document.upload_form.userfile_p#qprojects.req_part_id#_n+n.value;
    // process fileName
    n++;
	
function validateFileName(fileName){
   var extensions = ['.pdf', '.wtf'];
   
   var match = fileName.match(/\.[a-z0-9]{1,4}/ig);
   var i = match.length;
   
   while ( i > 0 && match[--i] in extensions ){}

   return !i;
} 
if ( !validateFileName(fileName) ){
    alert('Your upload form contains an unapproved file name.');
    // exit script
} 
}
</script>

Open in new window

0
 
LVL 1

Expert Comment

by:JerseyFoo
ID: 35141763
You're going to have to set id's for the elements and fetch them with document.getElementById('id');
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

775 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question