简体   繁体   English

客户端验证,修剪空白 - Rails 3 上的 client_side_validations gem 和 Ruby

[英]Client side validation, trim whitespace - client_side_validations gem and Ruby on Rails 3

I was trying to validate that a username has length > 2 on the client side, using the client_side_validations gem.我试图使用 client_side_validations gem 在客户端验证用户名的长度> 2。

Serverside in my model I had a before_validation filter to strip the whitespace, but on the client side, nothing would trim the whitespace.在我的 model 中的服务器端我有一个before_validation过滤器来去除空白,但在客户端,没有任何东西可以修剪空白。

How can I trim the whitespace to correctly count the number of characters in a field?如何修剪空格以正确计算字段中的字符数?

"Luke Skywalker " should count "Luke Skywalker". “卢克天行者”应该算“卢克天行者”。

I did it the following way:我是通过以下方式做到的:

in rails.validations.js that client_side_validations inserts, find the following part:在 client_side_validations 插入的 rails.validations.js 中,找到以下部分:

var validateElement = function(element, validators) {
    element.trigger('element:validate:before');

and add the following code after:并在之后添加以下代码:

element.val( element.val().trim() );

This strips the value of the DOM element and sends it to count the letters.这会剥离 DOM 元素的值并将其发送给计数字母。 This has the added benefit of trimming whitespace and replacing the text directly in the field.这具有修剪空白和直接在字段中替换文本的额外好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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