Page 1 of 1

Form Validation: can you check a 'File' has been attached?

Posted: Wed Nov 06, 2013 10:00 am
by simonmlewis
I am using a simple FILE form attachment, but I don't want the page to turn over, unless they select something.

I can easily do validation on Text fields, but don't know how to do it on:

Code: Select all

<input name='photo' type='file' />
This type of field.

I can make the page turnover, and if $photo has nothing in it, take em back, but by then they will have lost a load of details entered before.

Code: Select all

<script>
function formCheck(formobj){
	// Enter name of mandatory fields
	var fieldRequired = Array("firstname", "lastname", "email", "reason", "communication");
	// Enter field description to appear in the dialog box
	var fieldDescription = Array("Firstname","Lastname","Email","Reason","Communication");
	// dialog message
	var alertMsg = "You haven't quite finish the form:\n";
	
	var l_Msg = alertMsg.length;
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}

	if (alertMsg.length == l_Msg){
		return true;
	}else{
		alert(alertMsg);
		return false;
	}
}
// -->
</script>
This is the sort of validation I normally use. Doesn't work for the field name "photo" tho.
Is it possible??

EDIT:

I have found this, but don't know how to incorporate this into the existing validation script.

Code: Select all

<html>
<head>
<script type="text/javascript">
<!--//
function validateFileExtension(fld) {
	if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
		alert("Invalid image file type.");
		fld.form.reset();
		fld.focus();
		return false;
	}
	return true;
}
//-->
</script>
</head>
<body>
<form ...etc...
 onsubmit="return validateFileExtension(this.fileField)">
<p>
<input type="file" name="fileField"
 onchange="return validateFileExtension(this)">
<input type="submit" value="Submit">
</p>
</form>
</body>
</html>