0

Why the pattern in the input number doesn't work, I have the server error when I write 1.1, 1,1 because in the mvc controller method i should take the int type.

<input type="number" name="Quantity" min="1" title="Пожалуйста, введите количество" placeholder="кол-во" pattern="\d+" required />

the required work right.

How make the pattern to have only integer value?

3 Answers3

1

Wrapping your input in a form will make the validation take effect - it won't limit what people can type, but it will stop the form from being submitted if the input typed in isn't an integer.

const calc = () => alert("It worked!")
<form onSubmit="calc()">
  <input
    type="number"
    name="Quantity"
    min="1"
    title="Only ints please"
    placeholder="Type here..."
    pattern="\d+"
    required
  />
  
  <input type="submit">
</form>

If you want to limit what is being typed in the first place, you'll need more complicated JavaScript for that - see this answer for an example of how to do that.

James Whiteley
  • 3,363
  • 1
  • 19
  • 46
  • it doesn't help because it was in a form, but **Lawrence Cherone** was right `step = "1"` help me –  Mar 12 '19 at 14:31
  • You need to be careful with `step="1"` because it's not hugely backwards-compatible - though if that's not important in your site then that'll work fine. Just be careful that `step="1"` will also let through things like `e` as that counts as a number. – James Whiteley Mar 12 '19 at 14:41
0

Try \d+([.,]\d+)?.

"Digits, possibly followed by a . or , and more digits".

James Davis
  • 848
  • 8
  • 12
0

You must use javascript since the input contains "1.1" or "1" and not 1.1 or 1. Or you could convert the string to an int in your controller.

In JS, you can use parseInt(number, base), such as

let i = "42.5243";

let j = parseInt(i);
console.log(j); // 42

EDIT with snippet in comment :

<input type="number" name="Quantity" title="Пожалуйста, введите количество" placeholder="кол-во" pattern="\d+" required oninput="validity.valid ? this.save = value : value = this.save;" />

it won't allow the user to encode anything else than an integer.

Benjamin
  • 89
  • 5
  • It is one easy way, but how make by validation, because in my project the peple make order and choose the quantity of the product –  Mar 12 '19 at 14:10
  • Well, merging your input and a similar one I had answer previously, I came up with . it won't allow the user to input anything else than integer. src : https://stackoverflow.com/questions/55119386/input-number-does-not-limit-decimal-when-0-is-typed – Benjamin Mar 12 '19 at 14:25