Expand my Community achievements bar.

How to allow user to put only numbers and backspace?

Avatar

Level 3

Hello!

On my form i need to prevent user from typing anything but numbers in a specific field. But i also need to let user delete typed symbols.

For that porpuse i have a function:

function regExp(newsymbol){

    var re = /[0-9\b]/;

    if(newsymbol.length > 1)

    return "";

    else if (re.test(newsymbol)){

        return newsymbol;

    }else{

        return "";

    }

}

If i type backspace (trying to delete symbol) an "else" part of the expresion works.

So, how to fix my regexp, to let users delete symbols or are there any other ways to check if backspace is pressed (like keyCode and so on)?

6 Replies

Avatar

Level 8

I don't understand fully why you need to check if the backspace key is pressed since it sounds like you want them to be able to use it.

If you want to prevent them from entering numbers then put the following in the change event of the field:

if (!/\d/.test(xfa.event.change))

xfa.event.change="";

Kyle

Avatar

Level 5

You can also use the following code in the change-event:

if(xfa.event.newText.match(/[^0-9]/)){

xfa.event.change = "";

}

kind regards Mandy

Avatar

Level 8

Ah yes. Mine prevents entering numbers while yours prevents entering AND pasting.

I'd use your script.

Kyle

Avatar

Level 5

I'm really pleased to hear that "my" script was helpfull.?

Avatar

Level 3

Sorry, i've written it incorrectly: what do i need is to let user input numbers and only numbers. And i also need to let them delete incorrectly typed numbers, that is why i'm trying to 'catch' backspace symbol.

Avatar

Level 5

Sorry, but I don't understand. With "my" script the user can input only numbers in the field and he can delete an incorrect number.