1

我正在尝试上传文件。并使用此代码验证它

$(document).ready(function () {
  $('#form_model_upload').submit(function (e) {
    var isvalid = true;
    var val = $('#model').val();
    if (!val || val == "") {
      $('#err_model').html('please select an image');
      isvalid = false;
    } else {
      var ext = $('#model').val().split('.').pop().toLowerCase();
      if ($.inArray(ext, ['gif', 'jpg', 'jpeg']) == -1) {
        $('#err_model').html('invalid file extension').show();
        isvalid = false;
      }
    }
    return isvalid;
  });
});

这是我的html代码

 <form action="<?php echo $editFormAction; ?>" method="POST" name="form_model_upload">
        <input type="hidden" name="vendor_id" value="<?php echo $_SESSION['vendor_id']?>" /><tr><td></td><td><span id="err_model"></span></td></tr>
        <tr><td>Model:</td><td><input type="file" name="model" id="model"/></td>
        </tr>

        <tr><td>Description:</td><td><textarea rows="5" cols="30" name="description" id="description"  ></textarea></td></tr>
        <tr><td>Category:</td><td><select name="category_model" id="category_model">
        <?php $categories=$doc->getElementsByTagName("category");
        foreach($categories as $category)
        {//$category_node=$category->getElementsByTagName("cat_val");
        $category_value=$category->nodeValue;
        echo '<option value="'.$category_value.'">'.$category_value.'</option>';
        }?>

        </select> </td></tr>
        <tr><td></td><td><input type="submit" name="upload_submit" id="upload_submit" value="upload" /></td></tr>
        <input type="hidden" name="MM_insert" value="upload_model" />
        <input type="hidden" name="MM_insert" value="form_model_upload" />
       </form>

但即使验证失败它也会提交表单??我想防止表单提交验证失败。

4

1 回答 1

0
$(document).ready(function () {
  // move this var outside of submit
  var isvalid = false;
  $('#form_model_upload').submit(function (e) {
    // block submit if false (it will be the first time)
    if(!isvalid){ e.preventDefault(); }
    // set true state here before the validation test
    isvalid = true;
    var val = $('#model').val();
    if (!val || val == "") {
      $('#err_model').html('please select an image');
      isvalid = false;
    } else {
      var ext = $('#model').val().split('.').pop().toLowerCase();
      if ($.inArray(ext, ['gif', 'jpg', 'jpeg']) == -1) {
        $('#err_model').html('invalid file extension').show();
        isvalid = false;
      }
    }
    // if form is valid, submit form
    // isvalid is now true so e.preventDefault() wont fire
    if(isvalid){ 
        $(this).submit(); 
    }
  });
});
于 2013-01-17T20:47:49.287 回答