0

我是 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 部分中的代码(呈现此部分的实际 html 文件中没有太多内容,因为它是一个简单的 ajax 提交表单):

<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/>

4

1 回答 1

0

试试这个:

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

$('form[form_to_validate=user]').validate({
  ...
})
于 2012-06-21T22:09:27.747 回答