Checking if the entered user value in an HTML input is a float number

时间:2016-08-31 12:21:47

标签: html

I'm working on a HTML page on which i got some input controls. In these input controls the user shall enter a float number, p.e. "1234,56" with four integers before the point/comma and two integers behind (at maximum). How can i find out while or after entering the value, if the value is correct (number of integers before and behind the point/comma; only integers).

Thanks in advance!

1 个答案:

答案 0 :(得分:1)

我们可以通过将控件放在表单上,​​使用输入的pattern属性和提交按钮来比较模式和值来实现。

第一个例子:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Checking floatnumbers</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <form>
            <input type="text"
                   maxlength="7"
                   placeholder="____,__"
                   title="Please use format ####,##"
                   pattern="\d{1,4}(|\.|,)?\d{1,2}" />
            <br />

            <!-- For testing input patterns -->
            <input type="submit"
                   value="Submit" />
            <br /><br />

            <!-- Resets/clears the form -->
            <input type="reset"
                   value="Reset" />
        </form>
    </body>
</html>

首先,输入必须是“text”类型,而不是通常的“number”。 模式意味着用户可以/必须在点或逗号之前输入1到4个数字。 可以输入点/逗号和以下1到2的小数,但这不是必需的。

如果用户输入p.e. “12345”并单击提交按钮,它将显示属性标题中的文本错误。

也许有些用户不想输入像“1,23”这样的数字但是 - 因为他们匆忙 - 只是“,23”。 所以我们来看看第二个例子。

第二个例子:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Checking floatnumbers</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <form>
            <input type="text"
                   maxlength="7"
                   placeholder="____,__"
                   title="Please use format ####,##"
                   pattern="\d{0,4}(|\.|,)?\d{1,2}" />
            <br /><br />

            <!-- For testing input patterns -->
            <input type="submit"
                   value="Submit" />
            <br /><br />

            <!-- Resets/clears the form -->
            <input type="reset"
                   value="Reset" />
        </form>
    </body>
</html>

正如您可以看到点/逗号之前的输入最小值为0且最大值为4。 因此可以输入像“,23”这样的浮点数。

如果我们想在输入中输入negativ floatnumbers,我们将模式更改为"^[+-]?\d{0,4}(|\.|,)?\d{1,2}",将maxlength更改为8.

进一步通知 使用上面的模式,我们仍然可以输入像“12345”这样的数字,这在我们的例子中是不正确的。 正确的模式必须是:"^[+-]?\d{1,4}((\.|,)\d{1,2})?""^[+-]?\d{0,4}((\.|,)\d{1,2})?"

相关问题