Rataiczak24
Rataiczak24

Reputation: 1042

Adding and Removing Validation using RegEx on Input Fields

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.

Upvotes: 0

Views: 777

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

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));
  });

Upvotes: 1

Related Questions