如何验证我的输入字段以请求输入一些文本?

问题描述

我只是在做反向单词挑战。我有代码,并且一切正常,我只需要创建一个验证,要求用户输入某种类型的文本。目前,如果您单击“提交”,但该字段中没有任何文本,它仍然会返回这是一个回文。不知道在其中添加什么以请求一些文本或告诉用户他们需要输入文本。

document.getElementById("flipBtn").addEventListener("click",function () {

    //Here is what happens when the button is clicked.

    // Step 1 - Get the Data
    let inputWord = document.getElementById("reverseString").value;

    // Step 2 - Work with the Data
    let lowerInput = inputWord.toLowerCase();
    lowerInput = lowerInput.replace(" ","");
    let reverseWord = ""

    //First is the Loop Variable followed by a ;.
    //Second part is how many times we are looping. Until the second part is false.
    //Third is what happens after each loop. ++ means add 1,-- = subtract 1.
    //[] indicates array position.
    //A string is an array of characters.
    //string word = [w][o][r][d]
    //               0  1  2  3
    //Without the - 1 you get index out of range exception.
    //Maybe there is a JavaScript method to make all the letters LowerCase.
    //Maybe you want to store four variables,the original input,that reversed,and the lowercase version of each for comparison.
    for (let loop = inputWord.length - 1; loop >= 0; loop--) {
        reverseWord += lowerInput.charAt(loop);

    };
    let otherReverse = lowerInput.split("").reverse().join("");


    // Step 3 - Output the result
    if (lowerInput == reverseWord) {
        document.getElementById("reverseOutput").innerHTML = `The word that you entered: ${reverseWord} was changed to: ${otherReverse} is a Palindrome`;
    }
    else {
        document.getElementById("reverseOutput").innerHTML = `The word that you entered: ${reverseWord} was changed to: ${otherReverse} is not a Palindrome`;
    }

    document.getElementById("reverseString").addEventListener("keydown",function (e) {

        var character = (e.which) ? e.which : e.keyCode;

        if (character >= 97 && character <= 122 ||
            character >= 65 && character <= 90 || character == 8 || character == 9 || character == 32) {
            return true;
        }
        else {

            e.preventDefault();
            return false;
        }

    });
})
    <div class="container">
        <div class="row card"><span class="custfont">Reverse A String</span>
                <br />
                <div class="col"><input class="input" type="text" id="reverseString" placeholder="Enter your text..." /></div>
                <br />
                <div class="col"><button class="btn custbtn btn-dark button" id="flipBtn">Flip the String</button></div>
                <br />
                <div class="col"><span id="reverseOutput"></span></div>
        </div>
    </div>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)