以下验证可以正确验证代码并提供警报..但是一旦你关闭警报并希望继续,你就不能因为它自己刷新,我不希望页面刷新只是显示警报和让用户编辑他们的信息:
http://jsfiddle.net/PKLQn/114/
HTML:
<form name="fff1" onsubmit="return newfuncion();">
<input type="text" id="email" />
<input type="text" id="title" />
<input type="text" id="url" /><br><br>
<input type="file" id="flUpload" /><br/><br>
<input type="submit" value="CONTINUE" />
</form>
JAVASCRIPT:
function Checkfiles() {
var fup = document.getElementById('flUpload');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
var chkext = ext.toLowerCase();
if(chkext=="gif" || chkext=="jpg" || chkext=="jpeg" || chkext=="png") {
return true;
}
else { return false; }
} // Checfiles
function Checksize() {
var iSize = ($("#flUpload")[0].files[0].size / 1024);
alert(iSize);
if(Checkfiles()==true) {
alert("Checkfiles function works properly!");
if (iSize < 2097152.00) {
alert("It's smaller than 2 megabytes, proceed..");
return true;
}
else{
alert("It's bigger than 2mb, submit an smaller file!");
return false;
}
} else { alert("Upload GIF, PNG, JPG Images only"); return false; }
} //Checksize
function Checkfields() {
var error="";
// Validate Email
var email = $("#email").val();
if (/(.+)@(.+){2,}\.(.+){2,}/.test(email)) { } else { error += "- Please enter a valid email address.\n"; }
// Validate Title
var title = $("#title").val();
if (title=="" || title==null) { error += "- Please enter a valid title for your advertisement.\n"; }
// Validate URL
var url = $("#url").val();
if (/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/.test(url)) { } else { error += "- Please enter a valid URL."; }
if(error!=""){alert(error); return false;} else {return true;}
}// Checkfields
function newfuncion() {
var fields = Checkfields();
var size = Checksize();
var files = Checkfiles();
if(fields==true && size==true && files==true) {
alert("Code works, now proceed to .php page!");
return true;
} else {
alert("Something's wrong, check your code!");
return false;
}
} // Use all functions
不知道有什么不对吗?提前谢谢。
答案 0 :(得分:3)
您的Javascript中存在错误:
var iSize = ($("#flUpload")[0].files[0].size / 1024);
如果没有文件,访问size属性时会出错。
您需要先进行检查:
var iSize;
if ($("#flUpload")[0].files[0]){
iSize = ($("#flUpload")[0].files[0].size / 1024);
}