Wednesday, February 27, 2008

Restric the values in S:TextFields.

Hi all ,

Can some body please tell me a way to restrict the data that we can eneter to a textfield in struts2.

What I wanted to do is , for the s:textfield , I need to enter only

values these values {1-10 , +,-,.} .

Thank you.

  • Reply 1.

The only way I know would be to use JavaScript in an onkeyup handler that would check the entered value.

(*Chris*)

  • Reply 2.

On the server-side, use an expression validator to ensure the input contains only valid characters.

On the client-side either:

- use ajax validation; or

- use a javascript function that listens for the keypress event and rejects invalid keystrokes

As usual, the javascript keypress event on IE is different from all other browsers so the function has to include browser detection.

Here is the gist of what you need:

javascript:

function filterKeypress(e) {

var accept = /[\d|\+|\-|\.]/; // a regex pattern of accepted chars

var keyChar;

if (msie) { // use your favourite broswer detection function

keyChar = String.fromCharCode(e.keyCode);

} else {

keyChar = String.fromCharCode(e.which);

}

// check if the character is acceptable

if (!accept.test(keyChar)) {

e.preventDefault(); // if it's not, prevent the keypress event

from proceeding

}

}

  • Reply 4.

It works Thanks.

No comments: