This is my code, it is not working properly. It can be duped with "+++" or "---". I can prevent that but it is just increasing the validation. Is there any better way? Can the code be optimized?
var regexNumber = /^\$?(((\d)\,?)+)?((\d)+)(\.(\d)+)?$/;
$("#" + element).keydown(function (event) {
// Allow only backspace, delete, dot, arrow key, tab, shift+tab
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 || (event.keyCode>=37 && event.keyCode<=40) || event.keyCode==9 || event.keyCode==16) {
// let it happen, don't do anything
}
else {
// Allow copy, paste, select all only numbers
if (((event.keyCode == 65 || event.keyCode == 86 || event.keyCode == 67) && (event.ctrlKey === true || event.metaKey === true))) {
if (event.originalEvent.clipboardData.getData('Text').match(regexNumber) == null) {
event.preventDefault();
}
}
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
});
It should not allow: 1. Letters 2. Pasting data having letters
It should allow: 1. Digits with comma 2. Float 3. Tab, Shift+Tab 4. Ctrl + A, C, X, V 5. Backspace, Delete 6. Arrow keys 7. Pasting of data with comma and float
I think a regex to check letters and special characters except (.(dot) and ,(comma)) in a string and not allow them would work fine? But I don't what the regex should be?
I don't have much idea about regex.
I looked for similar questions, they were missing some cases from my validation.