草庐IT

javascript - 在 SELECT 元素的更改事件中重新验证输入

coder 2024-07-15 原文

我正在编写一个 AngularJS 应用程序,在这个应用程序中有一个域管理工具。 选择域后,我会在表中生成域记录,让用户编辑每一行。由于字段是动态创建的,我使用 ng-form 来启用单独验证每一行,因为它们共享相同的名称。

每个域记录都有一个内容字段,其中包含 IP、CNAME 等内容。我使用根据所选记录类型(A、CNAME、TXT 等)的函数生成的正则表达式模式验证此字段。

问题是,当我编辑 A 记录,然后将记录类型更改为 CNAME 时,表单仍然有效,因为没有对内容字段执行新的验证。我重新验证它的唯一方法是开始在内容字段中输入内容,然后就可以正常工作了。

检查下面的图片:

我在 A 记录上按编辑,一切看起来都很好:

我将记录类型更改为 CNAME,即使正则表达式已更改,表单仍然有效。当我更改类型时,我希望重新验证内容 (1.2.3.4),因为它是一个新的正则表达式:

我开始在内容字段中输入,现在表单正确地变为无效。我希望在更改记录类型时发生这种情况,而不仅仅是在我再次开始输入时发生:

#Slim version of the template to give you an idea on whats going on
<form novalidate name="recordForm" class="css-form" ng-controller="EditRecordCtrl">

    <table>

        <tr ng-repeat="record in domain.data.0" class="gradeA">

            <td ng-init="startingTypeData = record.type" class="domains-td" ng-switch on="record.edit">
                <span ng-switch-default>{{record.type}}</span>
                <span ng-switch-when="true">
                    <select ng-change="domainRecordContentType(record.type)" ng-init="domainRecordContentType(record.type)" ng-model="record.type" ng-options="c for c in domainRecordTypes" class="span12">
                    </select>
                </span>
            </td>

            <td ng-init="startingContentData = record.content" class="domains-td validation-dropdown-error-parent" ng-switch on="record.edit">
                <span ng-switch-default>{{record.content}}</span>
                <span ng-switch-when="true">
                    <ng-form name="innercContentForm">
                        <span class="validation-dropdown-error" ng-show="innercContentForm.content.$error.pattern">
                            {{ 'RECORD_EDIT_FORM_RECORD_CONTENT_PATTERN_MSG' | translate }} ( {{ record.type }} )
                        </span>
                        <input type="text" ng-model="record.content" name="content" required class="span12 edit-record-input" ng-pattern="domainRecordContentRegex.0" required />
                    </ng-form>
                </span>
            </td>

        </tr>

    </table>

</form>

更改下拉菜单时如何重新验证输入字段?

Plunker 示例:http://plnkr.co/edit/VAR5ho 笔记!第一行不显示 A 记录的小错误。您仍然可以像我在上图中所做的那样测试问题。

使用 Thomas 自定义指令更新

改变下拉菜单之前

将第一个下拉列表从 A 更改为 CNAME 后,所有内容字段都被删除

更新保存按钮

<button ng-disabled="recordForm.$invalid" ng-switch-when="true" ng-if="hideRecordType(record.type)" ng-click="recordForm.$valid && editRecord(record, domainId); record.edit=false; $parent.startingNameData=record.name; $parent.startingTypeData=record.type; $parent.startingContentData=record.content; $parent.startingTTLData=record.ttl; $parent.startingPrioData=record.prio" type="submit" class="btn btn-block btn-primary btn-icon" ><i></i>{{ 'DOMAINS_SAVE_BUTTON' | translate }}</button>

最后更新..关于编译元素的奇怪行为

我按下编辑,它进入我的正常编辑 View

我开始输入一个新的 IP 地址,直到它生效

如果我让内容在有效一次后无效,比如添加一个点,值就会被清除。为什么?

基于 Thomas 代码的当前指令:

domainModule.directive('revalidate', function($compile) {
    return {
        restrict: 'A',
        link : function (scope, element, attrs) {
          scope.$watch(attrs.ngModel, function (v) {
              var reg = scope.$parent.domainRecordContentRegex[0];

              if(!$(element).parent().parent().next().find('ng-form').find('input').val().match(reg)){

                  $compile($(element).parent().parent().next().find('ng-form').children('input[name="content"]').removeClass('ng-valid-pattern'))(scope);
                  $compile($(element).parent().parent().next().find('ng-form').children('input[name="content"]').addClass('ng-invalid-pattern'))(scope);

              }

            });
        }
    };
});

我现在选择实际字段并更改类以使其在正则表达式不匹配时无效。这样保存按钮也会失效。这在下拉列表中更改时有效,但它以某种方式破坏了编译的元素。

最佳答案

要触发验证,在 ng-change 的 select 中将输入值设置为它的值。将 plunker 中的第 44 行更改为

<select ng-change="domainRecordContentType(record.type);innercContentForm.content.$setViewValue(innercContentForm.content.$viewValue)" ng-init="domainRecordContentType(record.type)" ng-model="record.type" ng-options="c for c in types">

更新了 plunker http://plnkr.co/edit/D1AFHi

来源:https://stackoverflow.com/a/17102401/69362

关于javascript - 在 SELECT 元素的更改事件中重新验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18799543/

有关javascript - 在 SELECT 元素的更改事件中重新验证输入的更多相关文章

  1. ruby-on-rails - Ruby on Rails 迁移,将表更改为 MyISAM - 2

    如何正确创建Rails迁移,以便将表更改为MySQL中的MyISAM?目前是InnoDB。运行原始执行语句会更改表,但它不会更新db/schema.rb,因此当在测试环境中重新创建表时,它会返回到InnoDB并且我的全文搜索失败。我如何着手更改/添加迁移,以便将现有表修改为MyISAM并更新schema.rb,以便我的数据库和相应的测试数据库得到相应更新? 最佳答案 我没有找到执行此操作的好方法。您可以像有人建议的那样更改您的schema.rb,然后运行:rakedb:schema:load,但是,这将覆盖您的数据。我的做法是(假设

  2. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  5. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  6. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  7. ruby-on-rails - active_admin 目录中的常量警告重新声明 - 2

    我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA

  8. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  9. ruby - Capistrano 3 在任务中更改 ssh_options - 2

    我尝试使用不同的ssh_options在同一阶段运行capistranov.3任务。我的production.rb说:set:stage,:productionset:user,'deploy'set:ssh_options,{user:'deploy'}通过此配置,capistrano与用户deploy连接,这对于其余的任务是正确的。但是我需要将它连接到服务器中配置良好的an_other_user以完成一项特定任务。然后我的食谱说:...taskswithoriginaluser...task:my_task_with_an_other_userdoset:user,'an_othe

  10. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

随机推荐