Reputation: 3520
I am trying to restrict a user from being able to enter whitespace or hit the spacebar after characters (unless they enter a comma) as well as restrict all special characters except numbers and letters.
The desired output would be something like: "ab, c" or "abc, def, g, h..." The user would only be allowed to have whitespace or hit the spacebar after a comma. A comma is the only special character permitted.
What I have so far but it's only allowing for 1 comma:
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;
Upvotes: 2
Views: 1346
Reputation: 627022
To remove all whitespaces after a non-comma char, you can use this solution with no lookbehind:
.replace(/(^|[^,])\s+/g, "$1")
See this regex demo. Details:
(^|[^,])
- Capturing group 1 ($1
refers to this group value): start of string (^
) or (|
) any non-comma char ([^,]
)\s+
- one or more whitespaces.In your code:
function checkKey() {
var clean = this.value.replace(/[^\d,]/g, "").replace(/(^|[^,])\s+/g, "$1");
if (clean !== this.value) {
this.value = clean;
}
}
Upvotes: 2
Reputation: 163427
In your code .replace(/[^0-9,]/g, "")
, you are removing all chars except digits and a comma, not allowing chars a-z anymore.
You can first remove all characters except [^a-zA-Z0-9, ]+
, and then in browsers that support a lookbehind, you can allow a space when it is not directly preceded by a comma.
function checkKey() {
const clean = this.value
.replace(/[^a-zA-Z0-9, ]+/g, "")
.replace(/(?<!,) /g, "");
if (clean !== this.value) this.value = clean;
}
document.querySelector('input').oninput = checkKey;
<form>
<input type="text">
</form>
Upvotes: 3