BlackPearl
BlackPearl

Reputation: 2775

Validate input with Jquery

I am trying to do something like this code below but have so far not being successful.

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
    return true;
} // restrict numerical values only

The code above only allows for numerical characters, and when a user push any other key apart from the Numerical ones, it does not appear on the text box.

This is exactly what I want too but the scenario is different, I don't want the user to enter zero (0) as their first character.

e.g. 0909 wrong but instead 909

I have being able to achieve this thus far

$(".input-xlarge").keyup(function () {
    var textInField = this.value;

    if (textInField.length == 1) {
        if (textInField == 0) {
            showError('error?');
        }
    }
});

but instead a message should be shown to the user, the input should be ignored just like the first code.

Upvotes: 1

Views: 84

Answers (4)

Amir Popovich
Amir Popovich

Reputation: 29836

Look at the fiddle, this "blocks" the text box for only valid input via js.

HTML:

<input id='numeric' type='text'/>

JS:

$('#numeric').keydown(function(e){
    if(e.keyCode == 8) // allow backspace - add more chars here
    {
        return;
    }
    else if(e.keyCode < 48 || e.keyCode > 57 || (e.keyCode == 48 && $(this).val() == '')) // non numeric + beginning zero
    {
        e.preventDefault();
    }
});

Fiddle

Upvotes: 3

Bla...
Bla...

Reputation: 7288

Try this code:

$(".input-xlarge").keyup(function (event) {
    var textInField = this.value;

    if (textInField.substr(0, 1) == '0') {
        event.preventDefault();
        alert("should not start with zero');
    }
});

By doing this, whenever your user input 0 as the first letter, then it won't be showed and will alert an error message.

Upvotes: 1

Dave
Dave

Reputation: 4436

$( ".input-xlarge" ).keyup(function(e) {
  var textInField = this.value; 
  if (textInField.length == 1){
    if (this.value.length == 0 && e.which == 48 ){
      alert('cannot start with zero')
      return false;
   }
  }
});

refer this jsfiddle

Upvotes: 1

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

This would work,

$(".input-xlarge").keyup(function (evt) {
    var textInField = this.value;
    if (textInField.length == 1) {
        if (textInField == 0) {
            alert('number should not start with zero');
            $(evt.target).val("")
        }
    }
});

Upvotes: 1

Related Questions