javascript javascript中的字符串长度验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18804184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:17:00  来源:igfitidea点击:

String length validation in javascript

javascript

提问by Ashis Kumar

I have a small problem with a task I've been asigned. I'm trying to make an alert message appear if the length of the inputted number does not equal 7. The message appears even if the length of the number is equal to 7 and I can't figure out why, any help would be appreciated! thanks.

我被分配的任务有一个小问题。如果输入的数字的长度不等于 7,我正在尝试显示一条警告消息。即使数字的长度等于 7 也会出现该消息,我不知道为什么,任何帮助将不胜感激!谢谢。

var msg = "";

if (document.Entry.Number.length!== 7) {
            msg+="Your Number should be 7 digits. Please check this. \n";
            document.Entry.Number.focus();
            document.getElementById('Number').style.color="red";
            result = false;
        }
        if(msg==""){
            return result;
        }

        {
            alert(msg)
            return result;
        }

回答by Ashis Kumar

You can use document.Entry.Number.value.lengthin the ifcondition,

您可以document.Entry.Number.value.lengthif条件下使用,

var msg = "";

if (document.Entry.Number.value.length!== 7) {
            msg+="Your Number should be 7 digits. Please check this. \n";
            document.Entry.nNumber.focus();
            document.getElementById('Number').style.color="red";
            result = false;
        }
        if(msg==""){
            return result;
        }

        {
            alert(msg)
            return result;
        }

回答by Lorenz

That should work:

那应该工作:

if (document.Entry.Number.toString().length!== 7) {

If document.Entry.Number is a number, you'll have to convert it to a string to find out the length. (Ref Length of Number in JavaScript)

如果 document.Entry.Number 是数字,则必须将其转换为字符串以找出长度。(参考JavaScript 中的数字长度