Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 628
  • Last Modified:

does javascript have a wildcard

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
smfmetro10
Asked:
smfmetro10
  • 7
  • 6
  • 2
  • +2
1 Solution
 
Gurvinder Pal SinghCommented:
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
 
leakim971PluritechnicianCommented:
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
 
smfmetro10Author Commented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
HainKurtSr. System AnalystCommented:
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
 
JerseyFooCommented:
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
 
smfmetro10Author Commented:
@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
 
JerseyFooCommented:
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
 
HainKurtSr. System AnalystCommented:
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
 
smfmetro10Author Commented:
on a form dump the file names are
xxxx#n_1.pdf
xxxxx#n_2.pdf
xxxx#n_3.pdf etc

0
 
smfmetro10Author Commented:
@JerseyFoo: where would you put the alerts for people uploading something other than a pdf?

Javascript/jquery newbie

thanks
0
 
JerseyFooCommented:
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
 
smfmetro10Author Commented:
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
 
JerseyFooCommented:
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
 
smfmetro10Author Commented:
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
 
JerseyFooCommented:
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
 
smfmetro10Author Commented:
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
 
JerseyFooCommented:
You're going to have to set id's for the elements and fetch them with document.getElementById('id');
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 7
  • 6
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now