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
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]+
You should be using
document.getElementById("textArea").value
.Fixed version below:
You need to change your line:
To get the value like below:
Refer the below code for reference: