javascript:计算文本输入中的数字

标签 javascript html validation

我有一段 HTML,它创建了一个包含三个文本字段(名称、组和编号)的 Web 表单,所有这些文本字段都使用 JavaScript 进行验证以检查是否有数据输入到其中。在最后一个文本字段中,我需要引入一点额外的 JavaScript 来检查用户输入的数据是否也是四位数字(例如 2947 或 94Q3)。作为一个完整的 JavaScript 新手,我不确定我会怎么做!我是否必须创建一个变量来获取输入数据的值,然后计算变量的位数,或者我可以直接从字段中进行计算吗?这是我的代码的 Javascript 部分:

function validateForm() {
    var result = true;
    var msg = ””;
    if (document.Entry.name.value == ””) {
        msg += ”You must enter your name\n”;
        document.Entry.name.focus();
        document.getElementById(‘name’).style.color = ”red”;
        result = false;

        if (document.Entry.group.value == ””) {
            msg += ”You must enter the group\n”;
            document.Entry.group.focus();
            document.getElementById(‘group’).style.color = ”red”;
            result = false;
        }

        if (document.Entry.number.value == ””) {
            msg += ”You must enter the number\n”;
            document.Entry.number.focus();
            document.getElementById(‘number’).style.color = ”red”;
            result = false;
        }

        if (msg == ””) {
            return result;
        } {
            alert(msg)
            return result;
        }
    }

如果可能,您能告诉我需要插入什么代码吗?谢谢!

最佳答案

将此 block 放在您的条件列表中:

 if (document.Entry.number.length!=4) {
  msg+=”You must enter 4 digits \n”;
 document.Entry.number.focus();
 document.getElementById(‘number’).style.color=”red”;
 result = false;
}

关于javascript:计算文本输入中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026404/

相关文章:

javascript - 移动响应式下拉导航栏适用于小宽度浏览器,但不适用于我的手机

javascript - 传递参数

javascript - 诺基亚 map - 更改圆坐标

css - 在 Spring::Form 中使用额外的 cssErrorClass

javascript - 如何替换不在特定 div 中的字符串?

用于 UI 组件的 Javascript 包或库

html - <a href =""> 不工作

Node.js (Express) 表单在提交时清除

python - Django:如何使表单有条件?

javascript - 隐藏html页面源