Toniq
Toniq

Reputation: 5016

Input allow numbers and single comma

I have an input field in which I want to allow only number and 1 comma. How could I make it accept only single comma?

$("#my-field").on("keyup", checkKey);

function checkKey() {
    this.value = this.value.replace(/[^0-9,]/g, "");
}

Upvotes: 2

Views: 8194

Answers (1)

trincot
trincot

Reputation: 351369

You could do it like this:

function checkKey() {
    var clean = this.value.replace(/[^0-9,]/g, "")
                           .replace(/(,.*?),(.*,)?/, "$1");
    // don't move cursor to end if no change
    if (clean !== this.value) this.value = clean;
}

// demo
document.querySelector('input').oninput = checkKey;
<input>

This will remove all repeated commas, and everything between them. That is not an issue, since you press one key at a time.

Remarks

This blocking way of input validation is user unfriendly. It is better to colour things, or put messages, than to make the keyboard disfunctional.

Consider using the <input type="number"> element, which has number validation built in.

The input event is often more useful for checking for changes in the input than keyup, since changes can also be made via mouse actions and the context menu.

If you want to allow dot instead of comma, then change every , with \. in the regular expressions, as . has a special meaning in regular expressions, and must be escaped to be taken as a literal character.

Upvotes: 10

Related Questions