1

以下验证正确验证代码并发出警报。但是一旦您关闭警报并想要继续,您就不能因为它会自行刷新,我不希望页面刷新只是显示警报并让用户编辑他们的信息:

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

有什么问题吗?提前致谢。

4

1 回答 1

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);
}
于 2013-04-24T22:08:32.977 回答