Rails:Regx验证错误 - 无法读取addMethod

时间:2018-02-02 09:14:43

标签: jquery ruby-on-rails regex validation

我有一个表单,我想使用正则表达式进行验证,但它给了我以下错误:

(index):250 Uncaught TypeError:无法读取属性' addMethod'在HTMLDocument中未定义。 ((指数):250)

编辑:我忘了在javascripts / application.js中包含以下几行:

//= require jquery.validate.additional-methods
//= require jquery.validate

我现在看到一个稍微不同的错误:

  

jquery.validate.additional-methods.self-b6742ad35d3d82c2cb0ca5dc43bfffbc87063c90e0d8fd70714c5424128f408d.js体= 1:31

     

未捕获的TypeError:无法读取属性' addMethod'未定义的

     

$。validator.addMethod(" maxWords",function(value,element,params)

剧本:

$(document).ready(function(){
  var messages = {
    'nameRequired': "Naam is verplicht.",
    'emailRequired': "Voer een geldig e-mailadres in.",
    'bodyRequired': "Bericht is verplicht."
  };

  $.validator.addMethod("regx", function(value, element, regexpr) {
    return regexpr.test(value);
  });

  $('#new_message').validate({
    rules: {
      name: {
        required: true,
        minlength: 2,
        regex: /^[a-zA-Z]+$/
      },
      email: {
        required: true,
        regex: /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/
      },
      body: {
        required: true,
        minlength: 3,
        regex: /^[a-zA-Z\s]*$/
      },
    },
    messages: {
      name: messages.nameRequired,
      email: messages.emailRequired,
      body: messages.bodyRequired
    },
    onfocusout: function(element) {
      this.element(element);
    },
  });
});

HTML表单:

<%= form_for @message do | f | %>
  <div class="form-group">
    <%= f.label :naam %>
    <%= f.text_field :name, :class => 'form-control form__field small__field', required: true, name: 'name' %>
    <br />
    <%= f.label :email, 'E-mailadres' %>
    <%= f.text_field :email, :class => 'form-control form__field small__field', required: true, name: 'email' %>
    <br />
    <%= f.label :bericht %>
    <%= f.text_area :body, :class => 'form-control form__field', rows: 7, cols: 72, required: true, name: 'body' %>
    <br />
  </div>
  <%= f.submit "VERSTUUR", :class => 'btn--red btn__submit' %>
<% end %>

我使用的宝石:

gem 'jquery-validation-rails'
gem 'exception_notification'
gem 'jquery-rails'

1 个答案:

答案 0 :(得分:0)

(代表问题作者发布解决方案)

也许这对其他人有帮助。我通过切换来消除上述错误:

//= require jquery.validate.additional-methods
//= require jquery.validate

为:

//= require jquery.validate
//= require jquery.validate.additional-methods