Rails:jQuery验证插件无法正常工作?

时间:2012-06-21 21:44:47

标签: jquery ruby-on-rails jquery-plugins

我是Ruby的初学者,现在我正在尝试使用这个插件:

目前,我编写的用于验证简单rails表单中的名称,电子邮件和电话号码字段的javaScript验证代码无效。我可以在任何这些字段中输入任何内容或不输入内容,它将提交(这不是我想要发生的内容)。

这是我的/app/assets/javascripts/user.js.coffee文件中的代码:

$("#theform").validate({
rules: {
    name: {
        required:true,
        minlength:2,
        maxlength:50
    },
    email: {
        required: true,
        email: true
        minlength:2,
        maxlength:50
    },
    phone_number: {
        required: true,
        phoneUS: true,
        minlength:9,
        maxlength:20
    }
}
messages: {
    name: {
        required: "Please provide your name",
        minlength: jquery.format("At least {0} characters required!"),
        maxlength: "Too many characters!"
    },
    email: {
        required: "Please provide your email",
        email: "Your email address must be in the format of name@domain.com",
        minlength: jquery.format("At least {0} characters required!"),
        maxlength: "Too many characters!"
    },
    phone_number: {
        required: "Please provide your phone number",
        phoneUS: "Please provide a valid US phone number",
        minlength: jquery.format("At least {0} characters required!"),
        maxlength: "Too many characters!"
    }
}
});

这是我的/app/views/layouts/_form.html.erb partial中的代码(由于它是一个简单的ajax提交表单,因此呈现此部分的实际html文件没有太多内容):

<div id="theform">
<%= form_for(@user, :remote => true) do |f| %>

    Name: <div id='name'><%= f.text_field :name %></div><br/>
    Email: <div id='email'><%= f.text_field :email %></div><br/>
    Phone Number: <div id='phone_number'><%= f.text_field :phone_number%></div><br/>
    <%= f.submit "Submit" %>

<% end %>
</div>

以下是此表单的application.html.erb布局文件:

<!DOCTYPE html>
<html>
<head>
  <title>IntroProject</title>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= javascript_include_tag "jquery-1.7.2.min" %>
  <%= javascript_include_tag "jquery-validation-1.9.0" %>
  <%= csrf_meta_tags %>
</head>
<body>
<h1><%= image_tag("leaf_logo.png", alt:"Leaf") %> Sample Form </h1>
<div class="container">
    <%= yield %>
</div>
<br/>

    

1 个答案:

答案 0 :(得分:0)

试试这个:

<%= form_for(@user, :remote => true, :form_to_validate => 'user') do |f| %>

$('form[form_to_validate=user]').validate({
  ...
})