laravel 如何限制输入仅作为laravel中的数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35154100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:09:56  来源:igfitidea点击:

How to restrict input only as numbers in laravel?

laravel

提问by Sajin Shereef

I want to input only numbers while entering and restrict characters.

我想在输入和限制字符时只输入数字。

{!! Form::input('text','advertisement_height',null,['class'=>'form-control']) !!}

回答by mbklnd

You could change the input type to a number field.

您可以将输入类型更改为数字字段。

<input type="number" />

回答by Tutelage Systems

The Laravel validation class comes with a bunch of different number validators: https://laravel.com/docs/5.2/validation#available-validation-rules

Laravel 验证类带有一堆不同的数字验证器:https://laravel.com/docs/5.2/validation#available-validation-rules

You can see there is integerand numeric. If you have the request in your control you could just write the rules for it.

你可以看到有integernumeric。如果您可以控制请求,则可以为其编写规则。

// on your controller
public function store(Request $request)
{
  $rules = ['advertisement_height' => 'required|numeric'];
  $this->validate($request, $rules);
}

or you can create a validation object and run the validation on your input, however you get it.

或者您可以创建一个验证对象并在您的输入上运行验证,但是您会得到它。

回答by Popeye

{{Form::number('name','default_text',array('class' => 'form-control', 'required'))}}

{{Form::number('name','default_text',array('class' => 'form-control', 'required'))}}

use 'number' instead of 'text' and 'required' attribute for mandatory field.

对必填字段使用“数字”而不是“文本”和“必填”属性。

回答by yogesh chatrola

Try it here!

在这里试试吧!

<input id="txtnum" onkeypress="return isNumber(event)" type="text" name="txtnum">

Note that digits are allowed and alphabetic characters are not allowed. Observe, too, that arrow keys and backspace are allowed so that you can still edit what you type.

请注意,允许使用数字,不允许使用字母字符。还要注意,允许使用箭头键和退格键,以便您仍然可以编辑您键入的内容。

function isNumber(evt)
  {
     var charCode = (evt.which) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

     return true;
  }

Possible Answer: Allow only numbers to be typed in a textbox

可能的答案:只允许在文本框中键入数字

Fiddle: http://jsfiddle.net/Lm2hS/

小提琴:http: //jsfiddle.net/Lm2hS/

回答by MasterSith

Instead of "text" say "number":

而不是“文本”说“数字”:

Form::input('number'....

I think Form::number()...doesn't exist any more

我认为Form::number()...不存在了