开发者

How can I retrieve the value of a PASTE (copy-pasta) event in a GWT TextBox?

Hello fellow SO members,

I want to prevent the user from copy-pasting values in my TextBox IF AND ONLY IF the values do not respect a certain condition.

For instance, I created a DigitsOnlyTextBox which will be used for phone numbers. I already made it so only Character.isDigit characters can be typed into the box, and the user cannot copy-paste values into it, using :

this.sinkEvents(Event.ONPASTE);

and

public void onBrowserEvent(Event event) {
    sup开发者_如何学Goer.onBrowserEvent(event);

    // Permet d'empêcher le copier-coller, donc d'entrer des caractères non-numériques

    if (event.getTypeInt() == Event.ONPASTE) {
        event.stopPropagation();
        event.preventDefault();
    }
}

But I'd like to verify if the copy-pasted String is "digits only" and if so, let the event happen (therefore the text added).

tl;dr : see title

Thank you for your time. Sincerely.


According to the MDC:

There is currently no DOM-only way to obtain the text being pasted

IMO, you'd better let the "paste" happen and then "rewrite" the textbox's value to strip non-numerics (actually, I'd even rather do it onValueChange only) or simply flag the box as invalid when its value isn't numeric-only (this is what IntegerBox does for instance).


Just save the old value in a local variable and right after the event you excecute your logic and if the value is not ok just keep the old text.

@Override
public void onBrowserEvent(Event event)
{
    super.onBrowserEvent(event);
    final String oldValue = getValue();
    switch (event.getTypeInt())
    {
        case Event.ONPASTE:
            Scheduler.get().scheduleDeferred(new ScheduledCommand()
            {

                @Override
                public void execute()
                {
                    if(<not ok>)
                       setValue(oldValue);
                }

            });
            break;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜