1

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?

4
  • Your question is not clear. Commented 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? Commented May 28, 2019 at 4:37
  • Check this out stackoverflow.com/questions/475033/… Commented 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. Commented May 28, 2019 at 4:46

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Used acorn.Parser.parse(textarea.value) and installed acron using npm i acron, but it shows error
Usage as a module is different. Refer to the source code/documentation on the GitHub page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.