jquery验证插件不使用文件

时间:2014-11-14 04:40:13

标签: javascript jquery html forms validation

我使用jquery验证插件来验证表单。如果所有字段都留空,则可以正常工作。但是,如果我在输入字段中输入了一个文件并将其他必填字段留空,则它不再验证其他元素,只需将表单提交给服务器即可。

<script>
$().ready(function() {
    $("#form1").validate({
        submitHandler: function (form) {
            $.ajax({
                type: $(form).attr('method'),
                url: $(form).attr('action'),
                data: $(form).serialize(),
            })
            .done(function (response) {
                jAlert(response);      
            });
            return false; 
        },
        ignore: [],  
        rules: {
            title: {    required: true, minlength: 2,   maxlength: 25 },
            text1: {
                required: function() {
                    CKEDITOR.instances.text1.updateElement();
                }
            },
            text2: {
                required: function() {
                    CKEDITOR.instances.text2.updateElement();
                }
            },
            newsimage: {
                required: true,
                accept: "image/*"
            },
        },
        messages: {
            title: {
                required: "Please enter the Title",
                minlength: "Title must consist of at least 2 characters"
            },
            text1: {
                required: "Please enter text",
                minlength: "Must consist of at least 2 characters"
            },
            text2: {
                required: "Please enter text",
                minlength: "Must consist of at least 2 characters"
            }
        }
    });
});
</script>

这是表格

<form id="Form1" enctype="multipart/form-data" method="post" action="save.php" >

    Title: <input name="title" size="40" maxlength="255"> 
    <br>
    <label for="newsimage">News Image</label>
    <input type="file" id="newsimage" name="newsimage">

    <br> News Summary:
    <textarea id="text1" name="text1" rows="7" cols="30"></textarea>

    <script type="text/javascript">
            CKEDITOR.replace( 'text1' );
    </script>
    <br> News Full Story:
    <textarea id="text2" name="text2" rows="7" cols="30"></textarea>
    <script type="text/javascript">
            CKEDITOR.replace( 'text2' );
    </script>
    <br> <input type="submit" name="submit" value="Add News">

4 个答案:

答案 0 :(得分:0)

您可以在表单标签上使用required,如下所示:

<input name="title" size="40" maxlength="255" required>

应该强制一些输入。 (它没有消毒)

答案 1 :(得分:0)

由于我缺少additional-methods.js,因此我没有在我的工作结束,所以添加它可以解决问题。

<script src="js/additional-methods.min.js"></script>

答案 2 :(得分:0)

试试这个用户友好的验证插件

https://github.com/vanarajcs/jquery-form-validation

答案 3 :(得分:0)

首先要激活任何jquery验证库,您需要在jquery cdn下定义该库。您的结构应如下所示:

<!-- define jquery file -->
<!-- Now define jquery validation library -->

为了安全起见,请在标头上定义jquery文件,并在主代码后定义验证库。

相关问题