In my form, I have a text area. The textarea has to allow only javascript content. I have to validate the text area content, to check if it is javascript or not. How to check if the Text area contains data that is only valid javascript content?
-
Your question is not clear.Deepak Dixit– Deepak Dixit2019-05-28 04:32:51 +00:00Commented May 28, 2019 at 4:32
-
I have a form , which allows choosing a file of type js and allows to write jscode in textarea,how can i validate written jscode in textarea?Mariyam– Mariyam2019-05-28 04:37:18 +00:00Commented May 28, 2019 at 4:37
-
Check this out stackoverflow.com/questions/475033/…Nibin– Nibin2019-05-28 04:43:38 +00:00Commented May 28, 2019 at 4:43
-
If you want to validate the code of textarea you can do that by embedding eslint as a script. See eslint.org/docs/developer-guide/nodejs-api for more info.Deepak Dixit– Deepak Dixit2019-05-28 04:46:52 +00:00Commented May 28, 2019 at 4:46
Add a comment
|
1 Answer
Use a JavaScript parser like acorn and check whether you can correctly parse the textarea contents.
The snippet below uses acorn to try and parse the contents of two textareas, one containing valid JavaScript, and one just containing plain text.
function validateJs(textareaId) {
const textarea = document.getElementById(textareaId);
try {
acorn.Parser.parse(textarea.value);
} catch(e) {
textarea.style.backgroundColor = 'red';
return false;
}
textarea.style.backgroundColor = 'green';
return true;
}
validateJs('good');
validateJs('bad');
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/6.1.1/acorn.js"></script>
<textarea id="good" rows="4" cols="25">
function add(a, b) {
return a + b;
}
</textarea>
<textarea id="bad" rows="4" cols="25">
Hello world!
</textarea>
2 Comments
Mariyam
Used acorn.Parser.parse(textarea.value) and installed acron using npm i acron, but it shows error
Robby Cornelissen
Usage as a module is different. Refer to the source code/documentation on the GitHub page.