0

I have a dialog box that pops up after hitting an Add button. There are 2 fields, MR ID and Supplier ID. MR ID is a dropdown and shouldn't need any sort of validation. The supplier id is a text input and needs validation. It needs to be numbers only and there also can be no 2 supplier ids that are the same. They must be all unique. The code I have so far does not work in validating the supplier id.

HTML/PHP for dialog box:

<div id="dialog-form" title="Add Supplier ID">
  <p class="validateTips">All form fields are required.</p>

<!-- Dialog box displayed after add row button is clicked -->
  <form>
    <fieldset>
      <label for="mr_name">MR_ID</label>
      <select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
          <?php foreach($user->fetchAll() as $user1) { ?>
            <option selectedvalue="1">
                <?php echo $user1['MR_ID'];?>
            </option>
        <?php } ?>
      </select><br><br>
      <label for="buyer_id">Supplier ID</label>
      <input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99">

      <!-- Allow form submission with keyboard without duplicating the dialog button -->
      <input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
  </form>
</div>

JavaScript:

// ----- Dialog Box for adding supplier id -----

$( function() {


    $("#insertButton").on('click', function(e){
    e.preventDefault();
  });   

    var dialog, form,

      mr_id_dialog = $( "#mr_id_dialog" ),
      supplier_id = $( "#supplier_id" ),
      allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
      tips = $( ".validateTips" );
  console.log(allFields);

    function updateTips( t ) {
      tips
        .text( t )
        .addClass( "ui-state-highlight" );
      setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
      }, 500 );
    }

    function checkRegexp( o, regexp, n ) {
      if ( !( regexp.test( o.value ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
      } else {
        return true;
      }
    }

   function addVendor() {
      var valid = true;
      allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
      //valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
      valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Supplier ID" );
      console.log(allFields);
      if ( valid ) {
        var $tr = $( "#index_table tbody tr" ).eq(0).clone();
        var dict = {};
        var errors = "";
        $.each(allFields, function(){
          $tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
          var type = $(this).attr('id');
          var value = $(this).val();
          console.log(type + " : " + value);
          // ----- Switch statement that provides validation for each table cell -----
          switch (type) {
            case "mr_id_dialog":
                dict["MR_ID"] = value;
              break;
            case "supplier_id":
                dict["Supp_ID"] = value;
              break;
            }
        });
        $( "#index_table tbody" ).append($tr);
        dialog.dialog( "close" );
        console.log(dict);

        var request = $.ajax({
          type: "POST",
          url: "insert.php",
          data: dict
        });

        request.done(function (response, textStatus, jqXHR){
          if(JSON.parse(response) == true){
            console.log("row inserted");
          } else {
            console.log("row failed to insert");
            console.log(response);
          }
        });

        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });

        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {

        });


      }
      return valid;
    }

    var dialog = $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 400,
      width: 350,
      modal: true,
      buttons: {
        "Add Supplier ID": addVendor,
        Cancel: function() {
          dialog.dialog( "close" );
        }
      },
      close: function() {
        form[ 0 ].reset();
        allFields.removeClass( "ui-state-error" );
      }
    });

    form = dialog.find( "form" ).on( "submit", function( event ) {
      event.preventDefault();
      addVendor();
    });

    $( "#insertButton" ).button().on( "click", function() {
      dialog.dialog({
          position: ['center', 'top'],
          show: 'blind',
          hide: 'blind'
      });
      dialog.dialog("open");
    });
});

Samples that should pass:

349348
2
1234

Samples that should not pass:

01234
123 45 67
No hyphens, dashes, etc. Numbers only.
6
  • Please add to your description the expected input format for the Supplier ID field (e.g. 3 7?). I created a plunker with your sample code. Feel free to update/fork that and use it in your description Commented Dec 12, 2016 at 21:06
  • The input can be any sort of numbers, but not beginning with 0 Commented Dec 12, 2016 at 21:08
  • Your description contains there also can be no 2 supplier ids that are the same - are the supplier ids in that one string of numbers? or do you mean each digit must be unique? Commented Dec 12, 2016 at 21:16
  • each supplier id as a whole must be unique....there CAN be same digits in one supplier ID Commented Dec 12, 2016 at 21:21
  • Please provide samples of input that should pass and not pass the test (e.g. 123 should pass, 993 2 should fail, etc). Commented Dec 12, 2016 at 21:24

1 Answer 1

1

Per the jQuery documentation for the id-selector:

Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.

Instead of using the value property of the supplier_id, use the .val() function - because .val() will:

Get the current value of the first element in the set of matched elements

So update your function checkRegexp() like this:

function checkRegexp( o, regexp, n ) {
  if ( !( regexp.test( o.val() ) ) ) {
  ...

Also, when generating the option elements for the select list, selectedvalue is not a valid attribute. There are 4 attribute specific to option elements (in addition to the global attributes): disabled, label, selected and value.

$(function() {
    $("#insertButton").on('click', function(e){
    e.preventDefault();
  });   
    var dialog, form,
      mr_id_dialog = $( "#mr_id_dialog" ),
      supplier_id = $( "#supplier_id" ),
      allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
      tips = $( ".validateTips" );

    function updateTips( t ) {
      tips
        .text( t )
        .addClass( "ui-state-highlight" );
      setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
      }, 500 );
    }

    function checkRegexp( o, regexp, n ) {
      if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
      } else {
        return true;
      }
    }

   function addVendor() {
      var valid = true;
      allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
      valid = valid && checkRegexp( supplier_id, /^([1-9][0-9]*)$/g, "Please enter a valid Supplier ID" );
      if ( valid ) {
        var $tr = $( "#index_table tbody tr" ).eq(0).clone();
        var dict = {};
        var errors = "";
        $.each(allFields, function(){
          $tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
          var type = $(this).attr('id');
          var value = $(this).val();
          // ----- Switch statement that provides validation for each table cell -----
          switch (type) {
            case "mr_id_dialog":
                dict["MR_ID"] = value;
              break;
            case "supplier_id":
                dict["Supp_ID"] = value;
              break;
            }
        });
        $( "#index_table tbody" ).append($tr);
        dialog.dialog( "close" );
      }
      $('#console').append('valid: '+valid+'<br />');
    }

    var dialog = $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 400,
      width: 350,
      modal: true,
      buttons: {
        "Add Supplier ID": addVendor,
        Cancel: function() {
          dialog.dialog( "close" );
        }
      },
      close: function() {
        form[ 0 ].reset();
        allFields.removeClass( "ui-state-error" );
      }
    });

    form = dialog.find( "form" ).on( "submit", function( event ) {
      event.preventDefault();
      addVendor();
    });

    $( "#insertButton" ).button().on( "click", function() {
      dialog.dialog({
          position: ['center', 'top'],
          show: 'blind',
          hide: 'blind'
      });
      dialog.dialog("open");
    });
});
#console {
  float: right;
}
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<button id="insertButton">Insert</button>
<div id="dialog-form" title="Add Supplier ID">
  <p class="validateTips">All form fields are required.</p>
  <!-- Dialog box displayed after add row button is clicked -->
  <form>
    <fieldset>
      <label for="mr_name">MR_ID</label>
      <select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
      <br />
      <br />
      <label for="buyer_id">Supplier ID</label>
      <input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99" />
      <!-- Allow form submission with keyboard without duplicating the dialog button -->
      <input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px" />
    </fieldset>
  </form>
</div>
<div id="console"></div>

Edit: in your comments, you mentioned you have it mostly working though it doesn't accept zero followed by other digits but it does accept a single 0 (i.e. 0). If you remove the zero and the pipe from your regex, that should suffice. So the regex goes from:

/^(0|[1-9][0-9]*)$/

to

/^([1-9][0-9]*)$/

var nums = ['123', '99', '01234', '0', '00', '993 2'];
var pattern = /^([1-9][0-9]*)$/;
nums.forEach(function(numberString) {
  console.log('num: ',numberString,' pattern match: ',pattern.test(numberString));
  });

Sign up to request clarification or add additional context in comments.

7 Comments

The validation still is not working...wouldnt there have to be more changed then just the o.value changing to o.val?
perhaps it was also that I changed the first line to wait until the DOM is ready - see the updated explanation
this definitely works in your code snippet, but if i copy and paste the code in to my code, it still doesnt work....any idea why?
Hmm I am not really sure... Maybe try starting with my code and then slowly add in your pieces ensuring it still works along the way. I can try to make an example with Ajax enabled later today.
I made separate test files with just your code and it doesnt work...so it works here but not in separate code that I just made myself...hmm
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.