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?
Asked
Active
Viewed 87 times
1
-
Your question is not clear. – Deepak Dixit May 28 '19 at 04: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 May 28 '19 at 04:37
-
Check this out https://stackoverflow.com/questions/475033/detecting-programming-language-from-a-snippet – Nibin May 28 '19 at 04:43
-
If you want to validate the code of textarea you can do that by embedding eslint as a script. See https://eslint.org/docs/developer-guide/nodejs-api for more info. – Deepak Dixit May 28 '19 at 04:46
1 Answers
1
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>

Robby Cornelissen
- 91,784
- 22
- 134
- 156
-
Used acorn.Parser.parse(textarea.value) and installed acron using npm i acron, but it shows error – Mariyam May 28 '19 at 06:48
-
Usage as a module is different. Refer to the source code/documentation on the GitHub page. – Robby Cornelissen May 28 '19 at 06:58