Rails+jquery實現Ajax式註冊驗證

先放個效果圖上來看看:

下面來講明如何用rails+jquery實現這樣的註冊表單的ajax數據驗證:

基本的註冊,登陸模塊使用restful_authentication插件生成.

在註冊頁面,也就是sessions/new.html.erb中

<%content_for "head" do %>
  <%= stylesheet_link_tag "users/new"  %>

  <%= javascript_include_tag "jquery/users/register","jquery/users/jquery.validate" %>
  <script type="text/javascript">
      jQuery.validator.setDefaults({
          debug: true,
          success: "valid"
      });;
  </script>



<%end%>


<fieldset id="ologin"><legend>Register</legend>
  <div class="box">
    <%= error_messages_for :user %>
    <% form_for :user, :url => users_path, :html=>{:id=>"signupform"} do |f| -%>
      <table>
        <tr>
          
            <td><label for="login"><span>Login</span></label></td>
            <td><%= f.text_field :login %></td>
            <td class="status"></td>
        </tr>
        <tr>
          <td><label for="email"><span>Email</span></label></td>
          <td><%= f.text_field :email %></td>
          <td class="status"></td>
          
        </tr>
        <tr>
          <td><label for="password"><span>Password</span></label></td>
          <td><%= f.password_field :password %></td>
          <td class="status"></td>
        </tr>
        <tr>
          <td><label for="password_confirmation"><span>Confirm Password</span></label></td>
          <td><%= f.password_field :password_confirmation %></td>
          <td class="status"></td>
        </tr>
      </table>
      <div class="spacer"><%= submit_tag 'signup', :class=>"butt"%></div>
    
    <% end -%>
            
  </div>
</fieldset>



裏面爲了排版的整齊,我對錶單用了table格式.

這裏用到了三個js文件:jquery.js, jquery.validate.js, register.js

jquery.js和jquery.validate.js能夠到 jquery網站上下載.

register.js是自定義的jquery代碼:

register.js:
$(document).ready(function(){
 
    $("#signupform").validate({
        rules: {
            "user[login]": {
                required: true,
                minlength:5,
                remote: {
                   data: {
                        user_name: function(){
                            return $('#user_login').val();
                        }
                    },
                    url: "users/",
                    type: "get"
                   
                }

            },
           
            "user[password]":{
                required: true,
                minlength:6
            },
           
            "user[password_confirmation]": {
                required: true,
                minlength: 5,
                equalTo: "#user_password"

            },
           
            "user[email]":{
                required: true,
                email: true
            }
        },
        messages: {
                     "user[login]": {
                required: "Enter a username",
                minlength: jQuery.format("Enter at least {0} characters"),
                remote: "Already in use"
            },
           
            "user[password]":{
               required: "Provide a password",

                minlength: jQuery.format("Enter at least {0} characters")

            },
           
            "user[password_confirm]": {
                required: "Repeat your password",
                minlength: jQuery.format("Enter at least {0} characters"),
                equalTo: "Enter the same password as above"
            },

           
            "user[email]":{
              required: "Please enter a valid email address",
              minlength: "Please enter a valid email address"

            }
        },
        errorPlacement: function(error, element) {
           
                error.appendTo( element.parent().next() );

        },
        // specifying a submitHandler prevents the default submit, good for the demo
        submitHandler: function(form) {
            alert("submitted!");
                        form.submit();
        },
        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set &nbsp; as text for IE
            label.html("&nbsp;").addClass("checked");
        }
       
    });
   
           
});

這是jquery.validate這個插件的方法.

這段代碼能夠分紅這麼幾個部分

$("#signupform").validate({

         rules: {
            //對須要驗證數據添加各類規則
        },
messages: {
           //對未經過驗證的數據對應顯示的消息
        },
success: function(label) {
            //數據成功經過驗證以後,焦點轉移後的動做
        },
errorPlacement: function(error, element) {
           
           //設置消息顯示的位置

        },
submitHandler: function(form) {
            //當表單符合全部驗證規則以後,點擊"submit"以後的動做
        },
});

下面對這幾個部分分別來進行說明:
rules: {
            //對須要驗證數據添加各類規則
        },
jquery.validate提供了不少驗證的方法,具體內容能夠參考 API

比較經常使用的就是required()和remote了,required()方法就跟rails model裏的validates_presence_of方法同樣,驗證數據非空.

這裏拿用戶名驗證來講明它的用法:
"user[login]": { 
                required: true,
                minlength:5,
                remote: {
                   data: {
                        user_name: function(){
                            return $('#user_login').val();
                        }
                    },
                    url: "users/",
                    type: "get"
                   
                }

            },
下面這個是rails呈遞的html代碼:
  
  
           
  
  
<input id="user_login" name="user[login]" size="30" type="text" />



注意,在寫數據項驗證規則時,要使用input標籤的name屬性,譬如這裏
"user[login]"
remote是向server端發送ajax請求,要求從server端收到一個json數據
數據格式是key,value.譬如對於一個用戶名爲abc的數據,將它發到server端以後,
若是abc爲合法數據,那麼server端應該返回一個"abc",true這樣格式的數據.反之,若是不合法,就返回
"abc",false.

那麼remote內部,有三個參數,url指明server的地址, type指明http動做,data是傳遞的數據內容
data: {

              user_name: function(){

              return $('#user_login').val();

           }

       },

       url: "users/",

       type: "get"

}


這麼寫,我就將dom id爲user_login的輸入框內的數據傳遞給了users控制器,
方法爲get,很明顯在RESTful的架構中,這是傳遞到了users/index方法
(不過不知道爲何會傳遞兩個相同的值user[login]="val"和user_name="val")

那麼在index方法中:

def index
@user=User.find_by_login(params[:user_name])
if @user
json="\"#{params[:user_name]}\",false"
else
json="\"#{params[:user_name]}\",true"
end

respond_to do |format|
format.js {render :text=>json}
end
end

(這段代碼寫的比較噁心..不過湊乎能用)這樣就完成了這個數據項驗證的ajax請求..其餘的數據項基本上都是js式的驗證了.比較簡單就再也不詳述了.
相關文章
相關標籤/搜索