简体   繁体   中英

Rails : jQuery validation plug-in not working?

I'm a beginner coder in Ruby and currently I'm trying to use this plugin:

Currently however, the javaScript validation code that I have written to validate the name, email, and phone number fields in my simple rails form is not working. I can enter anything or not anything into any of those fields and it will submit (which is not what I want to occur).

Here's the code in my /app/assets/javascripts/user.js.coffee file:

$("#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!"
    }
}
});

Here's the code in my /app/views/layouts/_form.html.erb partial (the actual html file which renders this partial doesn't have much in it since it's a simple ajax submit form):

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

Here's the application.html.erb layout file for this form:

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

Try this:

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

And

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM