在输入字段上使用RegEx添加和删除验证

时间:2016-12-12 20:52:24

标签: javascript php html regex validation

我点击“添加”按钮后弹出一个对话框。有两个字段,MR ID和供应商ID。 MR ID是一个下拉列表,不需要任何类型的验证。供应商ID是文本输入,需要验证。它只需要数字,也可以没有2个相同的供应商ID。它们必须都是独一无二的。到目前为止,我所使用的代码无法验证供应商ID。

HTML / PHP对话框:

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

应该通过的样本:

349348
2
1234

不应传递的样本:

01234
123 45 67
No hyphens, dashes, etc. Numbers only.

1 个答案:

答案 0 :(得分:1)

the jQuery documentation for the id-selector

  

使用id选择器作为参数调用jQuery()(或$())将返回一个包含零个或一个DOM元素集合的jQuery对象。

不使用 supplier_id value 属性,而是使用.val()函数 - 因为.val()将:

  

获取匹配元素集中第一个元素的当前值

所以更新你的函数checkRegexp(),如下所示:

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

此外,在为选择列表生成option元素时, selectedvalue 不是有效属性。 选项元素有4个属性(除global attributes之外):已禁用标签已选择< / em>和

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

编辑:在你的评论中,你提到你有它主要工作,虽然它不接受零后跟其他数字,但它接受一个0(即0)。如果从正则表达式中删除零和管道,那就足够了。所以正则表达式来自:

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

/^([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));
  });