Maseeha Razzack
Maseeha Razzack

Reputation: 3

how to stop allowing or prevent minus symbol to enter text box more than once?

I have a textbox I have to stop allowing or prevent minus symbol to enter text box more than once. Can anyone help me on this?

Upvotes: 0

Views: 2960

Answers (3)

Nabin
Nabin

Reputation: 163

Html:

< input type="text" id="textBoxID" onkeyup="clickMe(this)" />

Using javascript:

function clickMe(obj)
{
    var textVal = obj.value;
    if (textVal.match(/\-/g).length > 1) {
        alert('you cannot enter - more than once');
    }
}

using jquery

//Jquery
$('#textBoxID').keyup(function () {
    var textVal = $(this).val();
    if(ele.match(/\-/g).length > 1)
    {
        alert('you cannot enter - more than once');
    }

});

Hope this helps

Upvotes: 0

cralfaro
cralfaro

Reputation: 5948

You could use jquery.validation http://jqueryvalidation.org/files/demo/ and add a rule with a regular expression so you can show a message/warning in that particular field to the user saying only one '-' symbol is allowed

Upvotes: 0

Starscream1984
Starscream1984

Reputation: 3062

You can stop more than one minus symbol in the textbox by applying a keydown handler and stopping the event if the minus symbol (key 45) is pressed AND there is already a minus sign in the input:

$("#MyInputID").keydown(function (e) {   
    if (e.keyCode == 45 && $("#MyInputID").val().indexOf('-') != -1) { 
        event.preventDefault();
    }
});

However, it is generally considered bad UX to block input, there might be a better solution for your exact needs - maybe validation, or using a number type input.

But the above should work if you are certain it's what you want to do.

(Also note, this approach won't stop someone pasting a value with more than one minus symbol - you'll need validation to deal with that.)

Upvotes: 1

Related Questions