仅正整数输入的Java验证 [英] Javascript Validation for Positive Integer Only Input

查看:94
本文介绍了仅正整数输入的Java验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文本框,仅允许使用正整数.如果输入了任何字母值或任何其他字符(例如%$& *£),则将显示错误消息,并且这些值不得呈现表格.

I have two text boxes, in it will only be allowed positive integers. If any alphabetical values or any other characters (e.g. %$&*£") are entered, an error message should be displayed and the values must not render a table.

 <input type="button" value="total" name="B3" onclick="powerOf();">

此行允许进行计算,该验证如何阻止这种情况的发生什么时候输入了不正确的值?截至目前,已计算出负数,输入字母会生成一个空表,这与我想要的不是完全一样:

This line allows for calculation to be made, how can this validation stop this from happening when the incorrect values are entered?? As of now minus numbers are calculated and entering alphabets produces an empty table which is not quite what I was going for:

(no1== no1.match(/^-\d+$/) ? alert("First number must be positive"): no1 = no1 ? no1 : 0);
        (no2== no2.match(/^-\d+$/) ? alert("Second number must be positive"): no2 = no2 ? no2 : 0)

        var range1 = parseInt(no1);
        var range2 = parseInt(no2);

有什么想法吗?

推荐答案

注意:您可以简单地通过HTML5表单验证来做到这一点:

Note: you can do this simply via HTML5 form validation:

<input type="number" min="1">

然后,除非输入的值大于1,否则您将无法提交表单.但这似乎仅在Chrome中有效.

Then you won't be able to submit the form unless the entered value is a number higher than 1. This only seems to work in Chrome though.

要回答您的问题,您要查找的是 event.preventDefault().如果您将onclick函数更改为:

To answer your question, what you're looking for is event.preventDefault(). If you change your onclick function to:

 <input type="button" value="total" name="B3" onclick="powerOf(event);">

然后您可以在 powerOf 函数中运行 event.preventDefault(),并且在运行该事件时,该事件将被取消".例如:

then you can run event.preventDefault() in the powerOf function, and when you run that, the event will be "cancelled". For example:

function powerOf(event) {
    if (!/^\d+$/.test(document.getElementById('input-1').value)) {
        event.preventDefault();
    }
}

当具有 id ="input-1" 的输入的值仅为不是位时,将取消单击事件.

that will cancel the click event when the value of the input with id="input-1" is not digits only.

有关工作示例,请参见此演示.

See this demo for a working example.

这篇关于仅正整数输入的Java验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆