jQuery验证-多次验证隐藏区域中的字段 [英] Jquery Validation - Validate several time a field in a hidden area

查看:110
本文介绍了jQuery验证-多次验证隐藏区域中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在表单上添加一些验证以添加联系人,但似乎做对了. 当您加载页面时,我的表单是隐藏的(使用CSS),并且您必须单击添加联系人"按钮以使其显示.然后,您会看到一个简单的表单,可以在其中输入名字(必填),姓氏和电子邮件地址(必填和电子邮件验证).完成后,单击添加",Jquery将对后端进行Ajax调用以在数据库中添加新联系人,并将刷新视图以显示新创建的联系人并隐藏表单. 当您添加第一个联系人时,它可以正常工作,但是如果您在未验证名字后尝试添加另一个联系人(如果重新加载页面,则可以工作).我真的不明白为什么会这样,我的猜测是因为我们已经第一次验证表单了,所以会破坏验证过程,但是我找不到.

I'm trying to add some validation on a form to add a contact and I can't seem to make it right. My form is hidden (with CSS) when you load the page and you have to click on the "add contact" button to make it appear. You then see a simple form where you can enter a first name (required), a last name and an email address (required and email validation). Once you are done, you click "add" and Jquery will do an Ajax call to the backend to add the new contact in the DB and will refresh the view to display the newly created contact and hide the form. When you add the first contact it works right but if you try to add an other contact right after the first name is not validated (works if you reload the page). I don't really understand why it's behaving like this, my guess is since we already validated the form a first time something is going that disrupting the validation process but I can't find what.

这是我的javascript

here is my javascript :

$(document).ready(function() {
  //get values //
  var service_name_value = $("#tbl-existing_emails tfoot tr td input[type='hidden']").val();


    /*****************  email management  ******************************/


        //add recipient function
        //triggered when user clicks on add recipient button
        //shows the form to enter the information for the new recipient+
        $('#btn-show_report_add').live("click" ,function(e) {

            if ($('#box-report').is(':visible')) {
                return false;
            }
            if (total_existing_emails < 3) {
                $('#box-report').show();
            }
            else {
                alert("You can have up to 3 extra emails");
            }
        });

        //hides the form to enter information for a new recipient
         $('#box-report button.cancel').click(function() {
             hideEmailForm();
        });

        //adds the email reicpient in DB
        $('#btn-report_add').click(function(e) {
            e.preventDefault();
            // Validate new email form
            $("#weeklyReportsForm").validate({
                debug : true,
                rules : {
                    fld_report_first_name : {
                        required: true
                    },
                    fld_report_email : {
                        required : true,
                        email : true
                    }
                }
            });

            if ($('#weeklyReportsForm').valid() ) { // New email data


                var new_recipient = {first  : $('#fld_report_first_name').val(),
                                 last : $('#fld_report_last_name').val(),
                                 email : $('#fld_report_email').val(),
                                 service_name : service_name_value
                };

                $.getJSON('/account/email-preferences/add-email', new_recipient, function(data) {
                    if(data.email == "fail"){
                        alert("It seems that the email you entered is incorrect.");
                    }
                    else if (data.status) {
                        addEmailRow(new_recipient.first, new_recipient.last, new_recipient.email, data.id);
                    }
                    else {
                        alert("Oops, we couldn't add this email.");
                    }
                });         
            }
        });



//////////// helper functions ////////////////
    function addEmailRow(first, last, email, id) {

        var new_row = '<tr data-id="'+id+'">';
        if (!id) {
            new_row += '<td>'+first+'<input type="hidden" name="recipients['+total_existing_emails+'][first]" value="'+name+'"/></td>';
            new_row += '<td>'+last+'<input type="hidden" name="recipients['+total_existing_emails+'][last]" value="'+last+'"/></td>';                       
            new_row += '<td>'+email+'<input type="hidden" name="recipients['+total_existing_emails+'][email]" value="'+email+'"/></td>';
        }
        else {
            new_row += '<td>'+first+'</td>';
            new_row += '<td>'+last+'</td>';
            new_row += '<td>'+email+'</td>';
        }
        new_row += '<td><button type="button" class="button cancel"><span class="icon"></span><span>Remove</span></button></td>';
        new_row += '</tr>';
        $('#tbl-existing_emails tbody').append(new_row);
        $('#row-nodata').remove();
        total_existing_emails++;
        hideEmailForm();
    }

});

这是有关表格的HTML:

and here is the HTML of the concerned table :

<table id="tbl-existing_emails" style="width:680px;">
  <thead>
    <tr>
                                        <th>First Name</th>
                                        <th>Last Name</th>
                                        <th>Email</th>
                                        <th></th>
                                        </tr>
                                    </thead>
                                    <tfoot>
                                        <tr>
                                        <td colspan="4">
                                            <button type="button" class="button add" id="btn-show_report_add" name="btn-show_report_add"><span class="icon"></span><span>Add Recipient</span></button>

                                            <div id="box-report" class="toggle">

                                                    <div class="row required">
                                                        <label for="fld_report_first_name">First Name</label>
                                                        <input type="text" name="fld_report_first_name" id="fld_report_first_name" value="{$REPORTRECIPIENT.first_name}" title="Enter the first name of a new recipient for this email.<br/><br/><em>Required</em><br/>Max 255 characters" />
                                                    </div>

                                                    <div class="row">
                                                        <label for="fld_report_last_name">Last Name</label>
                                                        <input type="text" name="fld_report_last_name" id="fld_report_last_name" value="{$REPORTRECIPIENT.last_name}" title="Enter the last name of a new recipient for this email.<br/><br/><em>Recommended</em><br/>Max 255 characters" />
                                                    </div>

                                                    <div class="row required">
                                                        <label for="fld_report_email">Email</label>
                                                        <input type="text" name="fld_report_email" id="fld_report_email" value="{$REPORTRECIPIENT.email}" title="Enter the new email address where this new recipient should receives this email.<br/><br/><em>Required</em><br/>Must be a properly formatted email address (e.g. psmith@homebuilder.com)"/>
                                                    </div>

                                                    <input type="hidden" id="fld_report_service_name" name="fld_report_service_name" value="WeeklyReport"/>

                                                    <div class="clear"></div>

                                                    <button class="button add" id="btn-report_add" name="btn-report_add" type="button"><span class="icon"></span><span>Add</span></button>
                                                    <button type="button" class="button cancel" name="btn_cancel"><span class="icon"></span><span>Cancel</span></button>

                                            </div>

                                        </td>
                                        </tr>
                                    </tfoot>
                                    <tbody>
                                        {foreach from=$REPORTRECIPIENTS item="REPORTRECIPIENT"}
                                        <tr data-id="{$REPORTRECIPIENT.id}" class="row box-existing_agent">
                                          <td>{$REPORTRECIPIENT.first}</td>
                                          <td>
                                            {$REPORTRECIPIENT.last}
                                          </td>
                                          <td><a href="mailto:{$REPORTRECIPIENT.email}">{$REPORTRECIPIENT.email}</a></td>
                                          <td>
                                            <button type="button" class="button cancel" name="btn_enail_cancel"><span class="icon"></span><span>Remove</span></button>
                                          </td>
                                        </tr>
                                        {foreachelse}
                                          <tr id="row-nodata">
                                            <td colspan="4">No recipients are associated with this email.</td>
                                          </tr>
                                        {/foreach}
                                    </tbody>
                                </table>

我真的不再去哪里找了,任何帮助将不胜感激!

I don't really where to look anymore and any help would be greatly appreciated !

谢谢

最大

推荐答案

它无法正常工作,因为您已将.validate()函数包装在click处理程序中.这意味着验证仅在单击后才初始化,而验证应在页面加载时初始化.

It's not working correctly because you've wrapped the .validate() function within a click handler. This means the validation initializes only after the click when it should initialize upon loading of the page.

$('#btn-report_add').click(function(e) {
        e.preventDefault();
        // Validate new email form
        $("#weeklyReportsForm").validate({ // <- this only initializes validation after the click
        ...

相反,这更像应该如何做(请参见官方演示的源代码)...

Instead, this is more like how it should be done (see source code of official demos)...

立即在您的表单上初始化Validation插件:

Immediately initialize the Validation plugin on your form:

 $("#weeklyReportsForm").validate({

     // validation rules and options

     submitHandler: function(form) {
         // optional- stuff to do upon form submission
     }
 ...

 });

将表单的submit绑定到元素的单击上:

Bind your form's submit to the click of your element:

 $('#btn-report_add').click(function(e) {

        e.preventDefault();

        // your other logic for click

        $("#weeklyReportsForm").submit();

 });

请参阅: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆