jQuery远程验证所有字段

时间:2016-05-07 15:13:02

标签: jquery ajax jquery-validate

我不接受我的PHP应用程序中的任何HTML,因此我打算阻止使用HTML标记提交的任何内容。我尝试添加以下JavaScript以向所有文本输入字段添加其他jQuery Validate规则。

我正在使用WordPress Ajax,因此动作和网址一起提交。

$('input[type="text"]').each(function() {
    $(this).rules('add', {
        remote:  {
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'ad_sanitize',
            }
        }
    });
});

以上js在Firefox控制台中返回错误

  

TypeError:a.data(...)未定义... ar d,e,f,g,h,i,j = this [0] if(b)switch(d = a.data(j) .form,“validator”)。设置,e = dr ..在Jquery,js

  $('#formname').validate({

    rules: {
       field1: 'required',
       field2: 'required',
    },
    message: {
       field1: 'Required',
       field2: 'Required'
   }
    submitHandler: function (form) {
        console.log('done');
   });

以上操作将指向以下功能服务器端

function isHtml($string) //This function just checks for html
{
    if ( $string != strip_tags($string) )
    {
        return true; // Contains HTML
    }
    return false; // Does not contain HTML
}

function ad_sanitize () { //<- This function calls when ajax call (Tested)

    foreach ($_POST as $key => $value) {
        if (isHtml($value) === true) {
            echo 'Only plain text allowed.';
        } else {
            echo true;
        }

    }
}

问题:当我添加上面的JavaScript时,我的jQuery Validate将不再起作用(未经验证提交的表单),当然,不会调用远程检查。

2 个答案:

答案 0 :(得分:0)

  

问题:当我添加上面的JavaScript时,我的jQuery Validate将不再起作用(未经验证提交的表单),当然,不会调用远程检查。

那是因为您已经破解了JavaScript,其中包含一些应该触发JavaScript控制台错误的语法问题:

  • 您已将<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/list" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="55dp" /> </RelativeLayout> 对象拼错为messages

  • 您在message对象后遗漏了逗号。

  • 您错过了messages功能的结束}大括号。

submitHandler

就服务器端代码而言:

Per remote documentation,服务器的响应必须为JSON字符串。如果您不将响应作为JSON编码的字符串回显,则$('#formname').validate({ rules: { field1: 'required', field2: 'required', }, messages: { // <- "messages" was misspelled here field1: 'Required', field2: 'Required' }, // <- comma was missing from here submitHandler: function (form) { console.log('done'); } // <- closing brace was missing from here }); 方法绝对不会起作用

remote

编辑:关注the docsfunction ad_sanitize () { foreach ($_POST as $key => $value) { if (isHtml($value) === true) { echo json_encode("Only plain text allowed."); // fail validation using this message } else { echo json_encode("true"); // pass validation // echo "true"; // also works the same (notice the quotes) } } } 的示例,使用函数...

data

答案 1 :(得分:0)

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script>
    $(document).ready(function() {
        $("#userForm").validate({
            rules: {
                name: {
                    required: true,
                    minlength: 3
                },
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true,
                    minlength: 8
                },
                conform_password: {
                    required: true,
                    minlength: 8,
                    equalTo: "#password"
                },
                gender: {
                    required: true
                },
                "hobby[]": {
                    required: true,
                    minlength: 1
                },
                address: {
                    required: true,
                    minlength: 10
                },
                country_id: {
                    required: true
                },
                state_id: {
                    required: true
                },
                image: {
                    required: true
                }
            },
            messages: {
                name: {
                    required: "please valid enter name"
                },
                email: {
                    required: "please valid email"
                },
                password: {
                    required: "the password is required"
                },
                conform_password: {
                    required: "this conform password is required",
                    equalTo: "please enter same password"
                },
                gender: {
                    required: "please select your gender"
                },
                "hobby[]": {
                    required: "please select your hobby"
                },
                address: {
                    required: "please Enter your address",
                    minlength: "minimum 10 character"
                },
                country_id: {
                    required: "please select one country"
                },
                state_id: {
                    required: "please select one state"
                },
                image: {
                    required: "please select your image"
                }
            },

            submitHandler: function(userForm) {
                userForm.insert();
            }

        });
    });
    $(document).ready(function() {
        $("#name").keypress(function(event) {
            var inputValue = event.charCode;
            if (!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
                event.preventDefault();
            }
        });
    });
</script>

<h2>User Register Form</h2>

<form id="userForm" name="userForm" class="form-horizontal" action="" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <div class="form-group">
            <label for="name">Name : </label>
            <input type="text" name="name" id="name" placeholder="Enter Your Name">

        </div>

        <div class="form-group">
            <label for="email">Email : </label>
            <input type="email" name="email" id="email" placeholder="Enter Your Email">

        </div>
        <div class="form-group">
            <label for="password">Password : </label>
            <input type="password" name="password" id="password" placeholder="Enter Your Password">

        </div>
        <div class="form-group">
            <label for="conform_password">Conform Password : </label>
            <input type="password" name="conform_password" id="conform_password" placeholder="Enter Your Conform Password">

        </div>
        <div class="form-group">
            <label for="gender" class="radio-inline gender"><b class="gender">Gender : </b>
                <input type="radio" name="gender" id="gender" value="male">&nbsp; &nbsp;Male
            </label>
            <label for="gender" class="radio-inline">
                <input type="radio" name="gender" id="gender" value="Female">&nbsp; &nbsp;Female
            </label>

        </div>
        <div class="form-group">
            <label for="hobby" class="checkbox-inline"><b class="hobbies"> Hobby : </b>
                <input type="checkbox" value="cricket" name="hobby[]" id="cricket" value="cricket">&nbsp; &nbsp;Cricket
            </label>
            <label for="hobby" class="checkbox-inline">
                <input type="checkbox" value="hockey" name="hobby[]" id="hockey">&nbsp; &nbsp;Hockey
            </label>
            <label for="hobby" class="checkbox-inline">
                <input type="checkbox" value="horserace" name="hobby[]" id="horserace">&nbsp; &nbsp;Horse Race
            </label>

        </div>
        <div class="form-group">
            <label for="address">Address : </label>
            <textarea class="form-control" id="address" rows="3" name="address"></textarea>

        </div>
        <div class="form-group">
            <label for="country_id">Select Country : </label>
            <select name="country_id" id="country_id">
                <option value="India">--select country--</option>
                <option value="India">India</option>
                <option value="India">USA</option>
                <option value="India">Rusia</option>

            </select>

        </div>
        <div class="form-group">
            <label for="state_id">Select State : </label>
            <select id="state_id" name="state_id">
                <option value="">--select state--</option>
                <option value="">rajasthan</option>
                <option value="">gujarat</option>
                <option value="">kerla</option>
            </select>

        </div>

        <div class="form-group">
            <input type="file" name="image" id="image" size="20" />

        </div>

        <button class="btn btn-primary" type="submit" id="insert" value="submit" name="insert">Add Submit</button>
</form>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        $('select[name="country_id"]').on('change', function() {
            var countryId = $(this).val();
            if (countryId) {
                $.ajax({
                    url: "<?php echo base_url();?>index.php/Crud/fetch_state/" + countryId,
                    type: "GET",
                    dataType: "json",
                    data: {
                        country_id: countryId
                    },

                    success: function(data) {

                        $('select[name="state_id"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="state_id"]').append('<option value="' + value.state_id + '">' + value.state_name + '</option>');
                        });
                    }
                });
            } else {
                $('select[name="state_id"]').empty();
            }
        });`enter code here`
    });
</script>