【问题标题】:Error in adding dynamic validation rules using jQuery Validator使用 jQuery Validator 添加动态验证规则时出错
【发布时间】:2015-12-09 03:38:30
【问题描述】:

我在 html 表单中使用 jQuery 验证器插件

客户端脚本Java Script/jQuery

服务器端脚本PHP

我先解释一下表格。我的表格包含:

a) 仅接受电子邮件 ID 的文本字段

b) 用于添加 cmets 的文本区域。

c) 用于输入用户名的文本字段

d) 用于输入手机号码的文本字段(仅接受号码)

a)b) 是我的表格的永久居民。无论发生什么,它们都会永远保持形式。他们就像家人一样。

c)d) 是临时的。它们的存在取决于a)。那是电子邮件 ID。

如果用户输入的电子邮件 ID 不包含在数据库中,则 c)d) 会起作用。用户必须输入他们的用户名和手机号码,并且所有四个字段都需要验证。如果不是,则仅验证前两个字段。我在这里有点搞砸了。

我正在使用客户端的 jQuery 验证器插件验证所有这些字段。服务器端也有验证。我不打算在这里。暂且略过。

为了检查电子邮件是否存在,我使用插件的远程功能。我尝试了两种方法来打开/关闭 c) 和 d) 的验证规则,但都失败了。 :)

<form role="form" id="product_description_form" name="product_description_form" method="POST" action="place_order_action.php" >
    <div class="col-md-6 col-sm-6 title bg-black">
        <div class="form-group">
            <input type="text" id="email_id" name="email_id"  class="form-control" placeholder="Email Address">
        </div>

        <div class="form-group">
            <textarea type="text" id="product_description" name="product_description"  class="form-control" placeholder="Comments"></textarea>
        </div>

        <div id="fullname_div" class="form-group" style="display:none;">
            <input type="text" id="full_name" name="full_name"  class="form-control" placeholder="Your Full Name">
        </div>

        <div id="mobilenum_div" class="form-group" style="display:none;">
            <input type="text" id="mob_num" name="mob_num"  class="form-control" placeholder="Contact Number">
        </div>

        <div class="col-md-12">
            <input type="submit" name="submit" id="finish" value="CONFIRM NOW" class="btn btn-primary" />
        </div>
    </div>
</form>

最初我将手机号码和姓名 div 隐藏起来。如果电子邮件 ID 不匹配,我将向用户显示它们。届时,名称和移动字段的类型将从隐藏更改为文本。否则,该类型将保持隐藏状态。我在某处听说隐藏字段没有得到验证。这就是我选择这条路线的原因。

一开始我想制作一个小提琴。但是我正在使用遥控器,所以它有点不合时宜,你知道的。也许吧。

这是我尝试过的第一种方法

$(document).ready(function() {
    $('#product_description_form').validate({
        rules: {
            email_id: {
                email: true,
                required: true,
                remote: {
                    url: "checkemail_exist.php",
                    type: "post",
                    dataType: 'html',
                    data: {
                        email_id: function() {
                            return $("#email_id").val();
                        }
                    },
                    success: function(dataa) {
                        var condition = dataa.trim();

                        //Invalid Data              
                        if (condition == "2") 
                        {
                            remove_validation();          
                            document.getElementById('email_id').value = '';
                            document.getElementById('mobilenum_div').style.display = 'none';
                            document.getElementById('fullname_div').style.display = 'none';
                            document.getElementById('mob_num').value = '';
                            document.getElementById('full_name').value = '';
                            alert('Please enter a valid email id.');
                        }
                        //Existing User
                        else if (condition == "1") 
                        {
                            remove_validation();           
                            document.getElementById('mobilenum_div').style.display = 'none';
                            document.getElementById('fullname_div').style.display = 'none';
                            document.getElementById('mob_num').value = '';
                            document.getElementById('full_name').value = '';
                            document.getElementById('mob_num').type = 'hidden';
                            document.getElementById('full_name').type = 'hidden';
                            alert('We will contact you.');
                        }
                        //New User
                        else if (condition == "3") 
                        {
                            add_validation();
                            document.getElementById('mob_num').type = 'text';
                            document.getElementById('full_name').type = 'text';
                            document.getElementById('mobilenum_div').style.display = 'block';
                            document.getElementById('fullname_div').style.display = 'block';
                            alert('New User.');
                        } 
                        else 
                        {
                            remove_validation();
                            document.getElementById('email_id').value = '';
                            document.getElementById('mobilenum_div').style.display = 'none';
                            document.getElementById('fullname_div').style.display = 'none';
                            document.getElementById('mob_num').value = '';
                            document.getElementById('full_name').value = '';
                        }
                    }
                }

            },
            product_description: {
                required: true,
                minlength: 10
            }

        },
        highlight: function(element) {
            $(element).closest('.form-group').removeClass('success').addClass('error');
        },
        success: function(element) {
            element.text('').addClass('valid')
                .closest('.form-group').removeClass('error').addClass('success');
        }
    });

function add_validation()
{
    $("#full_name").rules("add", "required");
    $("#mob_num").rules("add", {number: true, required:true, minlength: 10, maxlength:12 });
}

function remove_validation()
{
    $("#full_name").rules("remove", "required");
    $("#mob_num").rules("remove", {number: true, required:true, minlength: 10, maxlength:12 });     
}

}); 

你猜怎么着?它没有用。我知道,我知道我正在混合使用 jQuery 和 JavaScript。但这只是一个演示。 无论如何,在我的第一种方法成功失败后,我尝试使用插件的依赖属性。总有一个 B 计划。:D

这是我尝试的第二种方法

$(document).ready(function() {
    //Function to validate

    $('#product_description_form').validate({
        rules: {
            email_id: {
                email: true,
                required: true,
                remote: {
                    url: "checkemail_exist.php",
                    type: "post",
                    dataType: 'html',
                    data: {
                        email_id: function() {
                            return $("#email_id").val();
                        }
                    },
                    success: function(dataa) {
                        var condition = dataa.trim();

                        //Invalid Data              
                        if (condition == "2") 
                        {
                            document.getElementById('email_id').value = '';
                            document.getElementById('mobilenum_div').style.display = 'none';
                            document.getElementById('fullname_div').style.display = 'none';
                            document.getElementById('mob_num').value = '';
                            document.getElementById('full_name').value = '';
                            alert('Please enter a valid email id.');
                        }
                        //Existing User
                        else if (condition == "1") 
                        {
                            document.getElementById('mobilenum_div').style.display = 'none';
                            document.getElementById('fullname_div').style.display = 'none';
                            document.getElementById('mob_num').value = '';
                            document.getElementById('full_name').value = '';
                            document.getElementById('mob_num').type = 'hidden';
                            document.getElementById('full_name').type = 'hidden';
                            alert('We will contact you.');
                        }
                        //New User
                        else if (condition == "3")
                        {
                            document.getElementById('mob_num').type = 'text';
                            document.getElementById('full_name').type = 'text';
                            document.getElementById('mobilenum_div').style.display = 'block';
                            document.getElementById('fullname_div').style.display = 'block';
                            alert('New User.');
                        } 
                        else 
                        {
                            document.getElementById('email_id').value = '';
                            document.getElementById('mobilenum_div').style.display = 'none';
                            document.getElementById('fullname_div').style.display = 'none';
                            document.getElementById('mob_num').value = '';
                            document.getElementById('full_name').value = '';
                        }
                    }
                }

            },
            product_description: {
                required: true,
                minlength: 10
            },
            full_name: 
            {
                required: 
                {
                    depends: function(element) 
                    {
                        if (condition == "3") 
                        {
                            return true;
                        } 
                        else
                        {
                            return false;
                        }
                    }
                }

            },
            mob_num: 
            {
                required:
                {
                    depends: function(element) 
                    {
                        if (condition == "3") 
                        {
                            return true;
                        }
                        else 
                        {
                            return false;
                        }
                    }
                },
                number: true,
                minlength: 10,
                maxlength: 12
            }

        },
        highlight: function(element) {
            $(element).closest('.form-group').removeClass('success').addClass('error');
        },
        success: function(element) {
            element.text('').addClass('valid')
                .closest('.form-group').removeClass('error').addClass('success');
        }
    });

}); 

有时 B 计划也会失败。所以我们找到了一个C计划。就是这样。 我在哪里犯了错误?谢谢。

远程方法工作正常。我什至从 checkemail_exist.php 页面得到响应,并且成功中的 if-else 条件也被检查。但是验证规则并没有被相应地添加和删除。

【问题讨论】:

    标签: jquery jquery-validate


    【解决方案1】:

    你以错误的方式接近它,你可以隐藏元素然后验证规则将不会被应用。

    因此您可以设置验证规则,然后可以使用更改事件处理程序,该处理程序可以根据电子邮件是否存在来设置这些元素的显示。

    jQuery(function($) {
      $('#product_description_form').validate({
        rules: {
          email_id: {
            email: true,
            required: true,
          },
          product_description: {
            required: true,
            minlength: 10
          },
          full_name: {
            required: true
          },
          mob_num: {
            number: true,
            required: true,
            minlength: 10,
            maxlength: 12
          }
        }
      });
    
      $('#email_id').change(function() {
        //based on the value set the display state of those fields
        //as a temp implementation we will just toggle the display
        //using timeout to simulate a async ajax
        setTimeout(function() {
          $('#mobilenum_div, #fullname_div').toggle();
        }, 500);
      });
    });
    <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet" />
    <script src="http://code.jquery.com/jquery-1.11.3.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
    <form role="form" id="product_description_form" name="product_description_form" method="POST" action="place_order_action.php">
      <div class="col-md-6 col-sm-6 title bg-black">
        <div class="form-group">
          <input type="text" id="email_id" name="email_id" class="form-control" placeholder="Email Address">
        </div>
    
        <div class="form-group">
          <textarea type="text" id="product_description" name="product_description" class="form-control" placeholder="Comments"></textarea>
        </div>
    
        <div id="fullname_div" class="form-group" style="display:none;">
          <input type="text" id="full_name" name="full_name" class="form-control" placeholder="Your Full Name">
        </div>
    
        <div id="mobilenum_div" class="form-group" style="display:none;">
          <input type="text" id="mob_num" name="mob_num" class="form-control" placeholder="Contact Number">
        </div>
    
        <div class="col-md-12">
          <input type="submit" name="submit" id="finish" value="CONFIRM NOW" class="btn btn-primary" />
        </div>
      </div>
    </form>

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 2017-04-09
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多