简体   繁体   中英

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.

eg 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.

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

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("")
        }
    }
});

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.

$( ".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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM