简体   繁体   English

为什么Rails number_field表单构建器接受浮动值?

[英]Why Rails number_field form Builder accepts a floating value?

I have a rails form builder with number_field as follows: 我有一个带number_field的Rails表单生成器,如下所示:

= f.number_field :integer_value, :step => 1, :class => 'form', :value => obj.value

it generates the html as: 它生成的html为:

<input class="form" id="people_attributes_232322900500_integer_value" name="people[people_attributes][232322900500][integer_value]" placeholder="" step="1" type="number">

But still it accepts a float value. 但是它仍然接受浮点值。

params that I gets in server side is as 我在服务器端获得的参数是

{........, "integer_value"=>"12123.323"}

You still have to validate the number in the backend, for example: 您仍然必须验证后端中的数字,例如:

validates :integer_value,
  :presence => true,
  :numericality => { :only_integer => true, :greater_than => 0, :less_than_or_equal_to  => 100 }

For the input element, add min="0" to limit the values to integers. 对于输入元素,添加min="0"以将值限制为整数。 Still, it is possible for the user to enter a floating point number in all/most browsers. 用户仍然可以在所有/大多数浏览器中输入浮点数。

This is not a due to rails. 这不是由于滑轨引起的。 input type='number' is a HTML5 construct and it provides only number to be provided in this field. input type ='number'是HTML5构造,它仅提供此字段中要提供的数字。 It do not restrict user from entering non numeric characters. 它不限制用户输入非数字字符。

Though most of the browser would apply client side validation on this field and when you try to submit a form validation errors would be show. 尽管大多数浏览器都会在此字段上应用客户端验证,并且在您尝试提交表单验证时会显示错误。 Note: validation error depends completely on browser and browser version 注意:验证错误完全取决于浏览器和浏览器版本

You should apply server side validation on field to be sure that non numeric field is not accepted Check answer provided by zwippie for server side validation 您应该在字段上应用服务器端验证,以确保不接受非数字字段。检查zwippie提供的答案以进行服务器端验证

ref link: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_input_number 引用链接: http : //www.w3schools.com/html/tryit.asp? filename= tryhtml_input_number

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

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