【问题标题】:Checking input type in JS在 JS 中检查输入类型
【发布时间】:2019-01-03 17:37:34
【问题描述】:

我正在使用 typeof 命令来确保这个温度(摄氏度到华氏度)计算器的 2 个输入字段中只有一个填充了数据,并且它必须是一个数字。如果输入不是有效数字或两个字段均已填充,则应用程序将抛出错误消息。

问题:没有任何东西满足这个条件——errorMessage 总是显示出来,即使我输入了一个有效的数字。

typeof 是解决这个问题的正确方法吗?如果是,为什么这段代码不起作用?

document.getElementById('temperature-form').addEventListener('submit', calculateResult);

function calculateResult(e) {
    e.preventDefault();
    const celsiusInput = document.getElementById('celsius');
    const fahrenheitInput = document.getElementById('fahrenheit');
    let resultOutput = document.getElementById('result');
    // validate input data type and calculate result  
    if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) { 
        resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
    } else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
        resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';  
    } else {
        errorMessage('Please add a number in one of these fields');
    } 
}

非常感谢!

【问题讨论】:

  • DOM 元素不是数字。你可以有一个<input type="number">,其中 type 属性是数字,但元素的 typeof 不是。

标签: javascript forms validation if-statement typeof


【解决方案1】:

您可以使用isNaN() 函数检查每个输入的值属性以查看它们是否为数字,如下所示:

function calculateResult(e) {
    e.preventDefault();
    //Get the value of each input box
    const celsiusValue = document.getElementById('celsius').value;
    const fahrenheitValue = document.getElementById('fahrenheit').value;
    //Get the result element
    let resultOutput = document.getElementById('result');

    // validate input data type and calculate result  
    if(!isNaN(celsiusValue) && (fahrenheitValue === null || fahrenheitValue === "")){
        //Only celsiusValue has a valid number
        resultOutput.value = (celsiusValue * 1.8 + 32) + ' Fahrenheit';
    }else if(!isNaN(fahrenheitValue ) && (celsiusValue === null || celsiusValue === "")){
        //Only fahrenheitValue has a valid number
        resultOutput.value = ((fahrenheitValue - 32)/1.8) + ' Celsius';  
    }else if(!isNan(celsiusValue) && !isNan(fahrenheitValue )){
       //Both contain a valid number
       //Figure this one out as you didn't account for it
    }else{
       //Neither is a valid number
       errorMessage('Please add a number in one of these fields');
    } 
}

isNaN() 的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

【讨论】:

  • 非常感谢!那成功了。我之前尝试过 .value 但它不起作用,因为 typeof 不是这里的正确工具。 !isNaN 是关键 :) 再次感谢!
【解决方案2】:

在执行const celsiusInput = document.getElementById('celsius') 时,您得到的是DOM Element,而不是值。 为了获得价值,您必须检查属性value

所以你最终会得到这样的结果:

const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value

现在,如果我们使用typeof celsiusValue,我们将始终得到string,因为文本/数字输入始终接受文本(查看输入的type 属性以获取更多信息)。

检查是否有数字或字母的正确方法是使用Regular Expressions

我会留下一个简单的例子作为你的起点:

const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
if(/\D/.test(celsiusValue)) {
  alert("There is something that's not a number in the Celsius input!")
}

【讨论】:

  • 非常感谢!嗯,对我来说这是一个全新的星系。现在正在研究以掌握 regExp...
【解决方案3】:

首先通过像 fahrenheitInput === null 这样的比较,您将 DOM 元素与值 null 进行比较。

只有当 DOM 元素从未存在时才会评估为真。

其次,typeof 方法在 DOM 元素类型上的计算结果始终为 String,因此这始终为 false。

要真正得到你想要的,你必须做一个适当的检查

  1. 要检查是否提供了两个输入字段,只需检查值的长度即可:
if(fahrenheitInput.length > 0 && celsiusInput.length > 0) //fail
  1. 如果仅给出 fahrenheitInput:
if(!isNaN(Number(fahrenheitInput)) //convert
  1. 如果只给出 celsiusInput:
if(!isNaN(Number(celsiusInput)) //convert
  1. 最后,如果上面的所有检查都没有检查我们的,失败

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 2012-07-02
    • 2011-07-17
    • 2021-10-23
    • 2014-06-08
    • 1970-01-01
    • 2021-03-04
    相关资源
    最近更新 更多