最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

String length validation in javascript - Stack Overflow

programmeradmin7浏览0评论

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.

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;
        }

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.

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;
        }
Share Improve this question edited Sep 14, 2013 at 17:13 asked Sep 14, 2013 at 17:02 user2696190user2696190 0
Add a ment  | 

2 Answers 2

Reset to default 4

You can use document.Entry.Number.value.length in the if condition,

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;
        }

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)

发布评论

评论列表(0)

  1. 暂无评论