Search code examples
javascripthtmlthymeleaf

Validate HTML dynamically


I want to display the text with HTML tags.

I am having the following code:

<pre th:id="'answer' + ${answerStat.index}"></pre>
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/

$("#answer" + [[${answerStat.index}]]).html([[${answer.value}]]);

/*]]>*/
</script>

It works perfect, but answer.value was inputed by user earlier and it may contain syntax errors (like unclosed tag). And if answer.value contains the syntax error, it leads to error.

So, how can I dynamically check is answer.value has no syntax errors? Thank you, hope you will help me.


Solution

  • You can use a try/catch statement.

    The syntax is:

    try{
        //code to be tried here
    }
    catch(e){
        //error handling here
        //e is the error thrown by the try
    }
    

    So if your answer.value has an error, and it is inside a try/catch statement, the catch statement will run. See here for details.