1

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.

  • 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.
  • 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? (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();
    }
})
})
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
Luke
  • 35
  • 1
  • 7

3 Answers3

0

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.

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

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

I hope this helps you!

Ideal Bakija
  • 629
  • 5
  • 14
  • Unless the value is input without pressing any keys, whereupon this fails completely. :-( – RobG Aug 12 '14 at 12:28
  • Which part fails completely because I use the same code and it works fine? – Ideal Bakija Aug 12 '14 at 12:30
  • @IdealBakija— `The code below will not let the user enter character in your field only number`. That part fails if the user pastes or drags a value to the field (or enters content any other way that doesn't dispatch a keydown event). And since your code can't reliably stop entry of non–digits, simply checking for a non–empty field is insufficient validation. – RobG Aug 13 '14 at 01:57
  • For most cases it works. I tested the past command and it doesn't let you paste anything not just characters. Dragging is allowed. I guess there should be some other code preventing the other cases of character insertions. Until the type="number" is supported by all browsers. Thanks for the correction. – Ideal Bakija Aug 13 '14 at 08:18
0

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

Y.Puzyrenko
  • 2,166
  • 1
  • 15
  • 23
0

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:

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

       /* do validation */

    });

Within each, the function's this is set to the current element, so you can do:

     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). 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, e.g. 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).

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209