【问题标题】:How to invalidate form if user provides a bad image URL?如果用户提供了错误的图像 URL,如何使表单无效?
【发布时间】:2014-08-23 04:34:13
【问题描述】:

我在 jQuery 表单字段验证和图像 URL 方面遇到了一些问题。

  1. 如果明显有效的 URL 返回错误响应,我将无法成功阻止表单提交。

  2. 我看不到如何捕获和处理因测试 URL 而产生的警告/异常。

该应用程序是从 Google 电子表格中弹出的表单,使用 Google Apps 脚本准备数据,并使用 jQuery 以显示的 HTML 形式呈现数据。

我需要记录指向远程图像的超链接,该图像可能是也可能不是 HTTPS URL,我还需要获取并记录图像尺寸。我需要阻止表单提交,直到我可以成功保存图像的尺寸。


HTML:

<div id="divEditImageURL">
  Image URL : <input id="editImageURL" title="ImageURL" name="val_ImageURL">
  <div id="divImageURLresult"></div>
</div>

Javascript:

$("#WorkOrderEditor").validate({
   rules: {
       val_WorkOrderNumber: "required"
     , val_ImageURL: {
         required: true,
         url: true
       }
    }
   , messages: {
        val_WorkOrderNumber: "Please provide a valid work order number."
      , val_ImageURL: "Please provide the hyperlink to an image of the damage."
     }
   , submitHandler: function(form) {
      saveEditedWorkOrder();
  }
});

$( "#editImageURL" ).change(function() {
    var url = $( this ).val();
    console.log( "change() : " + url);
    $('<img/>').attr('src', url).on("load", function() {
         var img_dims = {w:this.width, h:this.height};
         console.log( "load() image width : " + img_dims.h + ":" + img_dims.w); 
         $('#editImageHeight').val(img_dims.h);
         $('#editImageWidth').val(img_dims.w);
         $('#divImageURLresult').html("Height : " + img_dims.h + ". Width : " + img_dims.w);
    }).error(function() { 
         console.log( "load() Bad URL "); 
         $('#editImageURL').val('Bad URL : ' + url);
         $('#editImageURL')[0].setCustomValidity("Uh Oh!");
         console.log( "load() Bad URL "); 
    });
});

高价值日志示例:

更改():http://i.imgur.com/Xgng8S9.png

页面位于 'https://docs.google.com/spreadsheets/d/1RHHD2zoI5j_aIBipYwQ7KUuKKxQHMjxLYmzjJv3En8s/edit#gid=709705542' 通过 HTTPS 加载,但显示的内容不安全 'http://i.imgur.com/Xgng8S9.png': 这个内容也应该被加载 通过 HTTPS。

load() 图像宽度:253:462


错误值日志示例:

更改():http://i.imgur.com/Xgng8S9.pig

页面位于 'https://docs.google.com/spreadsheets/d/1RHHD2zoI5j_aIBipYwQ7KUuKKxQHMjxLYmzjJv3En8s/edit#gid=709705542' 通过 HTTPS 加载,但显示的内容不安全 'http://i.imgur.com/Xgng8S9.pig': 这个内容也应该被加载 通过 HTTPS。

GET http://imgur.com/Xgng8S9.pig 404(未找到)

load() 错误的 URL

undefined 不是函数

注意:字段“#editImageURL”的值确实被替换为“Bad URL : http://imgur.com/Xgng8S9.pig”,但第二个控制台日志行从未执行。


我的问题:

  1. 为什么 "$('#editImageURL')[0].setCustomValidity('Uh Oh!');" 会抛出 "undefined is not a function" 以及我的替代方案是什么阻止表单提交?

  2. 如何捕获和禁止控制台日志,例如“此内容也应通过 HTTPS 加载”? (对于我的应用,HTTP URL 是可以预期的,但应用本身必须是 HTTPS)

【问题讨论】:

  • 不要使用 jQuery Validate 和一个完全独立的验证例程,为什么不使用这个插件提供的方法呢?您可以使用remote 使用服务器端函数进行验证,也可以使用addMethod() 编写自定义规则。通过在插件中工作,您可以保证阻止表单提交,直到您获得所需的内容(只要不绕过或禁用 JavaScript)。
  • 对不起? “使用此插件提供的方法”是什么意思?那是哪个插件?
  • 嗯,您的问题中使用的唯一插件...jQuery Validate 插件。
  • 啊哈,“而不是使用 jQuery Validate ......”这句话让我很困惑。我会更容易理解“你为什么不使用它提供的方法,而不是使用完全独立的验证例程和 jQuery Validate?”。所以我应该阅读 jQuery Validate 的 addMethod() 函数。会做。谢谢。
  • 你的建议很好——但它给我带来了一个新问题。验证器在每次击键后测试规则!在用户键入时测试每个变体的 URL 是不好的。如何仅在 onfocusout 时运行规则?

标签: jquery image jquery-validate


【解决方案1】:

除了使用 jQuery Validate 插件和一个完全独立的验证例程之外,为什么不使用这个插件提供的方法呢?您可以使用the remote method 针对服务器端脚本进行测试,或使用the .addMethod() method 编写自定义规则。通过在插件中工作,您可以保证阻止表单提交,直到您获得所需内容(只要 JavaScript 未被绕过或禁用)。

您也可以使用onkeyup: false 选项仅验证焦点不在。

在此处查看文档:http://jqueryvalidation.org/validate/


请参阅this answer,了解 OP 最终如何应用我的建议并解决了这个问题。

【讨论】:

  • 如果你更新你的答案,向未来的读者提出建议,让他们参考我的最终解决方案,我会将你的答案设置为正确答案。
【解决方案2】:

Sparky 为我指出了正确的答案,但让我在处理图像加载回调的正确方法上苦苦挣扎。

据我所知,自定义验证规则必须立即返回,这不允许进行远程调用并等待嵌入式回调。

我意识到我添加的验证必须始终返回“true”,并验证/使其他字段无效;图像尺寸之一是逻辑候选。另外,我不想显示图像尺寸字段,所以我将值写入文本

并设置其 CSS 类以反映最终验证状态。

这是我的第一部分问题的最终结果代码,其中穿插了 cmets。 我打算把第二部分变成一个新问题。


HTML

<div id="divEditImageURL">
    Image URL : <input id="editImageURL" title="ImageURL" name="val_ImageURL">
    <div id="divImageURLresult"></div>
</div>

<div id="divEditImageHeight"  class="label">
    Image Height : <input id="editImageHeight" title="ImageHeight" name="val_ImageHeight">
</div>

<div id="divEditImageWidth">
    Image Width : <input id="editImageWidth" title="ImageWidth" name="val_ImageWidth">
</div>

Javascript

/*  Invalidate the image height immedately upon any change to the image URL  */
$( "#editImageURL" ).change(function() {
  $('#editImageHeight').val("Unknown");
});

/*  Rather than show these numbers in disabled data entry */
/*    fields, 'divImageURLresult' will be shown instead.  */
$( "#divEditImageHeight" ).hide();
$( "#divEditImageWidth" ).hide();

/*   Vew validation rule added to jQuery Validation */
$.validator.addMethod(
      "remoteImage"  // This is the name of the new rule, applied to 'val_ImageURL' below.
    , function (url, element) {
        $('#divImageURLresult').removeClass("invalid").removeClass("validated"); // Clear previous simulated validation results
        $('<img/>').attr('src', url).on("load", function() {
           $('#editImageHeight').val(this.height);
           $('#editImageWidth').val(this.width);
           $('#divImageURLresult').html("Height : " + this.height + ". Width : " + this.width);
          $('#divImageURLresult').addClass("validated");  // Simulated validation result
        }).error(function() { 
           $('#editImageHeight').val("Unknown"); // Force validation to fail. Height can only be a number.
           $('#divImageURLresult').html("Not an image.");
           $('#divImageURLresult').addClass("invalid");  // Simulated validation result
        });
        return true;  // Always return true since we get here before the image load callback returns.
      }
    , "");


$("#WorkOrderEditor").validate({
   // Specify the validation rules
   rules: {
       val_WorkOrderNumber: "required"
     , val_ImageURL: {
           required: true
         , url: true          // Must ba a valid URL
         , remoteImage: true  //  This is the new rule added above, it always tests
       }                      //  valid, but it puts the load result in editImageHeight 
     , val_ImageHeight: {
         required: true,
         number: true          // Must ba a valid integer
       }
     , val_ImageWidth: {
         required: true,
         number: true          // Must ba a valid integer
       }
    }

   , messages: {
        val_WorkOrderNumber: "Please provide a valid work order number."
      , val_ImageURL: "Please provide the hyperlink to an image of the required work."
      , val_ImageHeight: "The URL does not point to a valid image."
     }
   , errorClass: "invalid"
   , onkeyup: false  //  Do NOT validate on every key stroke
   , ignore: []      //  Ignore "hidden" state of fields, and validate them anyway.
   , submitHandler: function(form) {
      saveEditedWorkOrder();
  }
});

公平地说,考虑到他提供的所有帮助,我将 Sparky 的答案设置为正确的答案。他已经对此做出了回答,以便未来的读者知道它已经尝试和测试了示例代码。 Up Votes,如果这对您有帮助,请帮助其他人找到它并始终不胜感激:-)

【讨论】:

    猜你喜欢
    • 2022-11-02
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多