skip to Main Content

I am trying to build a function in JavaScript that prints "valid input" in console if all characters in the textbox are other than alphabets (upperCase, lowerCase). But if any of character in the textbox is alphabet then it prints "valid input". I used a button to invoke this function.

Test case for more understanding:

  • "Lorem ipsum dolor sit amet" (valid)
  • "54646475" (invalid)
  • "#$#$" (invalid)
  • "Lorem ipsum 655746 dolor sit amet" (valid)
  • "Lorem ipsum dolor sit #$%^ amet" (valid)
  • "Lorem ipsum 7746 dolor %$^& sit amet" (valid)

I am confused about logic building of this problem.

Firstly I go with regular expression but didn’t understand how to implement it in this problem.

function capCaseHandle() {
        const allCharRegExp = /[w]+/;
        let text = document.getElementById("textArea");
        if (allCharRegExp.test(text)) {
                        console.log("Valid Text");
        }
        else {
            console.log("Invalid Text");
        }
    }

I tested this function but the function itself is invalid.

3

Answers


  1. The biggest issue that I’m seeing is you’re testing a regular expression against a DOM Element, not the text within that element. You can access the value of an element with .value.

    Another issue is w+ will match numeric text. If you only want alpha characters try upper and lowercase ranges for [A-Za-z]+

    function capCaseHandle() {
        const allCharRegExp = /[A-Za-z]+/;
        let textElement = document.getElementById("textArea");
        let text = textElement.value;
        
        if (allCharRegExp.test(text)) {
            console.log("Valid Text");
        } else {
            console.log("Invalid Text");
        }
    }
    
    Login or Signup to reply.
  2. You should be using document.getElementById("textArea").value.

    Fixed version below:

    function capCaseHandle() {
      const allCharRegExp = /[w]+/;
      let text = document.getElementById("textArea").value;
      if (allCharRegExp.test(text)) {
        console.log("Valid Text");
      } else {
        console.log("Invalid Text");
      }
    }
    
    Login or Signup to reply.
  3. You need to change your line:

    let text = document.getElementById("textArea");
    const allCharRegExp = /[w]+/;
    

    To get the value like below:

    let text = document.getElementById("textArea").value;
    const allCharRegExp = /[a-zA-Z]/;
    

    Refer the below code for reference:

    function validateInput() {
        const text = document.getElementById("textArea").value;
        const allCharRegExp = /[a-zA-Z]/;
    
        if (allCharRegExp.test(text)) {
            console.log("Valid input :"+text);
        } else {
            console.log("Invalid input :"+text);
        }
    }
    <textarea id="textArea"></textarea>
    <button onclick="validateInput()">Check Input</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search