简体   繁体   English

使用Jquery验证输入

[英]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. 这也正是我想要的,但是情况有所不同,我不希望用户输入零(0)作为他们的第一个字符。

eg 0909 wrong but instead 909 例如0909错误,但改为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. 看看小提琴,这“阻塞”了仅通过js进行有效输入的文本框。

HTML: HTML:

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

JS: 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. 这样,每当用户输入第一个字母0 ,它就不会显示,并且会提示错误消息。

$( ".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 参考这个jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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