validate edit box input text length on xPage

784 views Asked by At

When I enable field length validation it validates only when I submit the form...

<?xml version="1.0" encoding="UTF-8"?>

<xp:inputText id="inputText1">
    <xp:this.validators>
        <xp:validateLength maximum="20"
            message="You can input max 20 characters">
        </xp:validateLength>
    </xp:this.validators>
</xp:inputText>
<xp:message id="message1" for="inputText1"></xp:message>

so how to show the error message once user typed in 21st character? Assume need a code for CSJS...

1

There are 1 answers

3
Knut Herrmann On BEST ANSWER

Add an client side event handler "onkeyup" to your inputText control:

    <xp:eventHandler
        event="onkeyup"
        submit="false">
        <xp:this.script><![CDATA[
            thisEvent.srcElement.value = thisEvent.srcElement.value.substring(0, 20)
        ]]></xp:this.script>
    </xp:eventHandler>

It shortens the text to max length if necessary.

You can show the message as alert

            var element = thisEvent.srcElement;
            if (element.value.length > 20) {
                element.value = element.value.substring(0, 20);
                alert("You can input max 20 characters");
            }

or you can add a client message text field to your XPages and fill it with the message whenever the max length was reached

<xp:inputText id="inputText1">
    <xp:this.validators>
        <xp:validateLength  maximum="20"
            message="You can input max 20 characters">
        </xp:validateLength>
    </xp:this.validators>
    <xp:eventHandler
        event="onkeyup"
        submit="false">
        <xp:this.script><![CDATA[
            var element = thisEvent.srcElement;
            var message = document.getElementById("#{id:clientMessage}");
            if (element.value.length > 20) {
                element.value = element.value.substring(0, 20);
                message.innerHTML = "You can input max 20 characters";
            } else {
                message.innerHTML = "";
            }
        ]]></xp:this.script>
    </xp:eventHandler>
    </xp:inputText>
<xp:text id="clientMessage" value="" />