使用 jquery 验证插件验证表单输入类型文件类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10883512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:53:16  来源:igfitidea点击:

validate form input type file type using jquery validate plugin

jqueryjquery-pluginsjquery-validatevalidation

提问by MAK

the following code: script code

以下代码:脚本代码

<script type="text/javascript">
$(document).ready(function() {
    $("#formElem").validate({

        rules: {  

            dimage:{
                minlength:200    
            }  
        },
messages: {


             dimage:{
               required: 'Please select the image!'  
            } ,

        }       
    });

});
</script>

html code

html代码

<form id="formElem" name="formElem" action="" method="post">

 <input type="file" name="dimage" id="dimage" />
</form>

I'm using jquery validate.js file for client side validation. when i create a file with above code it's not showing any error message.

我正在使用 jquery validate.js 文件进行客户端验证。当我用上面的代码创建一个文件时,它没有显示任何错误消息。

How should i alert the error message when the user not selected the file?

当用户未选择文件时,我应该如何提醒错误消息?

采纳答案by ShankarSangoli

Try this.

尝试这个。

$(document).ready(function() {
    $("#formElem").validate({
        rules: {  
            dimage:{
                required: true    
            }  
        },
        messages: {
            dimage:{
               required: 'Please select the image!'  
            } ,
        }       
    });
});

回答by Seeker

If your uploading an image file Jquery Validation plugin have a option acceptyou can set that to a value which will validate that if the file is really an image then your jquery code will be like this:

如果您上传图像文件 Jquery 验证插件有一个选项,accept您可以将其设置为一个值,该值将验证该文件是否确实是一个图像,那么您的 jquery 代码将如下所示:

$("#formElem").validate({

      rules: {  

            dimage:{
                    required: true,
                    accept:"jpg,png,jpeg,gif"
                }  
        },
    messages: {

            dimage:{
                    required: "Select Image",
                    accept: "Only image type jpg/png/jpeg/gif is allowed"
                }  

             }      
        });

for more information See Official Docs

有关更多信息,请参阅官方文档