简体   繁体   English

文本框是否在Javascript中接受以下值?

[英]textbox accepts the following values in Javascript?

I have a textbox and i need to validate that it accepts only 1,1.5,2,2.5,3,3.5,...11.5 How to validate it.. pls tell the answer please. 我有一个文本框,我需要验证它仅接受1,1.5,2,2.5,3,3.5,... 11.5如何验证它。请告诉答案。

 $(document).on('keyup', '#Dia_Inch', function (e) {
        Dia_Inch = $(this).val();


        if (Dia_Inch.charAt(1) == ".") {
            if (Dia_Inch.charAt(2) != "5") {
                this.value = '';
                $('#Dia_Inch').val("");
                alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
                return false;
            }
        }

        var val = isNumberInch(e);
        if (val == false || Dia_Inch > 11.5) {
            this.value = '';
            $('#Dia_Inch').val("");
            alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
            return false;
        }

    });

this my sample code.. but it wont be worked. 这是我的示例代码..但无法使用。

You can do this using jquery: 您可以使用jquery执行此操作:

function validate(value){
  var arr = [1,1.5,2,2.5,3,3.5,...11.5];
  if($.inArray(value, arr) >= 0){
    return true;
  }
return false;
}

You'll have to modify this according to your needs. 您必须根据需要进行修改。

Here is a fiddle: http://jsfiddle.net/5Cm2w/ 这是一个小提琴: http : //jsfiddle.net/5Cm2w/

Do not forget to update the array with your actual values. 不要忘记用您的实际值更新数组。

This may solve your purpose. 这可以解决您的目的。

$(function() {
    $('button').on('click', function() {
      var val = $.trim($('input[type="text"]').val());
        if(val.length && $.isNumeric(val) && val.match(/^\d+(\.5{0,1})?$/)) {
           alert('valid')
        } else {
            alert('invalid');
            $.trim( $('input[type="text"]').val('') );
        }
    });
});

Demo 演示

But if u want to allow up to 11.5 then 但是,如果您想允许最多11.5,则

$(function() {
    $('button').on('click', function() {
      var val = $.trim($('input[type="text"]').val());
        if(val.length && $.isNumeric(val) && val.match(/^[1-9]{1}[1]{0,1}(\.5{0,1})?$/)) {
           alert('valid')
        } else {
            alert('invalid');
            $.trim( $('input[type="text"]').val('') );
        }
    });
});

Demo 演示

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

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