Validators with TextBoxes

Supposing I want to create a text field which only accepts numbers. What is the best way to do that?

Currently,
I am creating a separate class called NumBox which is supposed to create a textField which will show a validator with a message whenever a non digit is entered. What am i doing wrong here?

[[code]

public class NumBox extends TextField
{
TextField textboxForNumber;
public NumBox()
{
textboxForNumber = new TextField(“Enter a numeric value”);
textboxForNumber.setColumns(5);
Validator numberValidator = new RegexpValidator(“\d”, “You must enter a number”);
textboxForNumber.addValidator(numberValidator);
textboxForNumber.setImmediate(true);
}
}

[/code]

Will validators only work if the field is associated with a form? Is there another way to do it? Any help would be greatly appreciated.

Rohith

That pattern only matches to one digit. You probably want to use “\d*”

Thanks for pointing that out. However, the validator still does not pop up. What am i doing wrong?

Rohith

Your code should work. Notice that immediate textfield sends value to server for validation when it loses focus.

I read your code wrong, it doesn't work. You don't need that extra member inside extended textfield.

 public class NumBox extends TextField
 {
     public NumBox()
    {
          setCaption("Enter a numeric value");
          setColumns(5);
          Validator numberValidator = new RegexpValidator("\\d*", "You must enter a number");
         .addValidator(numberValidator);
          setImmediate(true);
    }
}