简体   繁体   English

验证输入类型=“数字”

[英]validate input type=“number”

I try to do some programming: I have this order form with different input fields (name, amountOfProductA, amountOfProductB, amountOfProduct...) and I submit this form, after some validation, with a jquery script. 我尝试进行一些编程:我有一个具有不同输入字段(名称,amountOfProductA,amountOfProductB,amountOfProduct ...)的订单表单,经过一些验证,我使用jquery脚本提交了此表单。

  • I plan to reuse the code and the number of product fields may vary form time to time. 我打算重复使用该代码,并且产品字段的数量可能会随时间而变化。
  • In the validation I make sure that at least one of the (type="number") product input fields is filled in. 在验证中,我确保至少填写(type =“ number”)个产品输入字段之一。
  • If a user types a number in one of the product inputfields and by mistake a character (or a number and a character) in the other the form submits with this later field empty. 如果用户在产品输入字段之一中输入数字,而错误地在另一个产品输入字段中输入了字符(或数字和字符),则该表单将提交,而此后面的字段为空。
  • Because the wrong filled in field submits empty I cannot validate this. 由于错误填写的字段提交为空,因此我无法对此进行验证。

Can you please give me a clue how validate this? 您能给我个提示如何验证吗? Should I just juse type="text" input fields? 我应该只使用type =“ text”输入字段吗? (How do I check if at least one product field is filled in then?) (然后如何检查至少一个产品字段?)

This is my code: 这是我的代码:

jQuery(function ($) {
$('#bttn-submit').click(function () {

    $('input').css('background', '#fff'); // reset BGcolor

    var formOk = true;
    var allProdFields = $('input[type=number]') // Selection of all Product('number') fields
    var numberOfProdFields = allProdFields.length; // How many ('number') fields are there?

    // How many product fields are empty?
    var prodFieldsEmpty = 0;
    for (i = 0; i < numberOfProdFields; i++) {
        if( $(allProdFields[i]).val() == '' || $(allProdFields[i]).val() == 0){
            prodFieldsEmpty++;
            }
    }
    // Is there at least one product field filled?
    if(prodFieldsEmpty == numberOfProdFields){
        var formOk = false; 
        alert('Form not OK');
        allProdFields.css('background', '#f30302');
    }

    // Is the name field filled?
    if( $('#pesoonNaam').val() == '') {
        $('#pesoonNaam').css('background', '#f30302');
        var formOk = false; 
    }

    if( formOk == true ) {
        document.actieForm.submit();
    }
})
})

The code below will not let the user enter character in your field only number. 下面的代码将不允许用户在您的仅字段数字中输入字符。 Because the type="number" is html5 and doesn't work in all the browsers. 因为type =“ number”是html5,因此无法在所有浏览器中使用。

   $(document).on('keydown', '.numeric-input', function(event) {
        var dot_split = $(this).val().split('.');
        if ($.inArray(event.keyCode,[46,8,9,27,13]) !== -1 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39) && dot_split.length <= 2) {
            // let it happen, don't do anything
            return;
        }else{
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
    })

Then you can check with an .each if any of the fields is empty. 然后,您可以使用.each检查是否有任何字段为空。

prodFieldsEmpty = 0;
$('.numeric-input').each(function(){
   if($(this).val() != ""){
      prodFieldsEmpty++;
   }
})

I hope this helps you! 我希望这可以帮助你!

You can try smth like: 您可以尝试如下:

function checkInputs(){
   result = false;
   $('input[type="number"]').each(function(){
       if($(this).val() != '' && isNumeric($(this).val())) result = true;
   })
   return result;
 }

UPD: Fiddle UPD: 小提琴

You should not attach validation to the submit button as the user can submit the form without pressing it, attach validation to the form's submit handler: 您不应该将验证附加到提交按钮,因为用户可以在不按下表单的情况下提交表单,而是将验证附加到表单的提交处理程序:

jQuery(function ($) {
    $('#formID').submit(
        ...

jQuery has an each method for iterating, so: jQuery具有每种迭代方法,因此:

    $('input[type=number]').each( function(index) {

       /* do validation */

    });

Within each , the function's this is set to the current element, so you can do: each中 ,该函数的this设置为当前元素,因此您可以执行以下操作:

     if (this.value == 0) {
        prodFieldsEmpty++;
     }

The value of a form control is always a string, so the test this.value == 0 will return true if the value is '0' or '' (empty string). 表单控件的值始终是字符串,因此如果值是'0''' (空字符串),则测试this.value == 0将返回true。 If you don't like using type coercion, then do: 如果您不喜欢使用强制类型,请执行以下操作:

     if (this.value === '0' || this.value === '') {

If you want to check that the value is an integer, then there are any number of answers here about that, the simplest is probably the accepted answer here : 如果要检查该值是一个整数,那么有任何数量的关于这里的答案的,最简单的是可能接受的答案在这里

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Note that this will allow all types of numbers, eg 2.34e3. 请注意,这将允许所有类型的数字,例如2.34e3。 If you just want to allow say positive integers, you can try: 如果您只想说正整数,可以尝试:

function isPositiveInt(n) {
  return /^\d+$/.test(n);  // or return !/\D/.test(n)
}

Again, there are many ways to approach that. 同样,有很多方法可以解决这个问题。

Rather than count the number of fields and then the number that pass, if you only want to check that at least one passed, set a flag: 如果只想检查至少一个通过,则设置一个标志,而不是先计算字段的数目,然后再计算通过的数目。

    var passNumeric = false;
    $('input[type=number]').each( function(index) {

      if (isNumber(this.value)) {
        passNumeric = true;

      } else {
        // do something with fails?
      }
    });

You can use the else branch to do something with the fails (or nothing). 您可以使用else分支对失败进行处理(或不执行任何操作)。

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

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