-3

Validation: I need only number space and plus symbol in a textbox

$('#value').bind('keypress', function (e) {
    if ($('#value').val().length == 0) {
        if (e.which == 32) { //space bar
            e.preventDefault();
        }
        var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122);
        if (!valid) {
            e.preventDefault();
        }
    } else {
        var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122 || e.which == 32 || e.which == 95 || e.which == 8);
        if (!valid) {
            e.preventDefault();
        }
    }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dinup
  • 3
  • 8
  • If you `console.log(charCode);` before the `if` what is logged for space? – mjwills Oct 27 '17 at 13:20
  • Please do not use the [tag:jquery-validate] when the question has nothing to do with this plugin. Edited. Thanks. – Sparky Oct 27 '17 at 16:07
  • In this above code i just want the space-bar key to work..number and plus symbol key is working but space- bar key is not working – Dinup Oct 30 '17 at 09:43

1 Answers1

0

I believe you are approaching this the wrong way. The term you are looking for is "validation", and there are many good ways to go about it. I recommend you look into this StackOverflow post. Regular expressions are the way to go, though you could also do this with pure HTML5 without needing to get Javascript involved. Look into this and this.

Alex Eggers
  • 328
  • 3
  • 16
  • I dont want specific format, But I need a textbox which will not allow alphabet but rest all key should work – Dinup Oct 30 '17 at 09:48