Question

I have custom tag which contains form with text input and submit. I want to validate this text input using JS, so my custom tag output should look like:

<script type="text/javascript">
    function validate(form) {
        var text = form.textInput;
        // validation code
    }
</script>

<form onsubmit='return validate(this);'>
    <input type='text' name='textInput'/>
    <input type='submit'/>
</form>

(Note, this code simplified!)

My problem appears when I want to use this tag twice or more times at page - I want to print form at page again, but not JS validation code! Validation code must be unique at the page. How can I archive that? My custom tag extends javax.servlet.jsp.tagext.TagSupport

Was it helpful?

Solution

I found the most suitable solution for me.

Class javax.servlet.jsp.tagext.TagSupport contains protected field pageContext which presents... page context! I can easily access context attributes of javax.servlet.jsp.PageContext. So, I put next code in my custom tag:

public int doStartTag() throws JspException {
    if (pageContext.getAttribute("validated") == null) {
        // validation code writing
        pageContext.setAttribute("validated", true);
    }
    ...
}

If condition would be reachable only once per page rendering.

Hope it would be useful for someone.

OTHER TIPS

I suggest you to try to embed that JavaScript function in some .js file an import that file. If you don't want to do that, for some reason you should try to define that function dynamically, if it is not defined:

if (typeof window.validateMyForm === 'undefined') {
    window.validateMyForm = function(form) {
        var text = form.textInput;
        // validation code
    }
}

As you guess this should define function only if it is not already defined.

First answer is correct, but that means that programer must know where in code are already inserted custom tags and according to that this whether to set that parameter to true or false. And what about code changes, you will have to always go thought whole page and revise all used tags on a page.

Make the custom tag to accept a parameter that toggles the validation on or off, and of course have it generate different code depending on the value of the parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top