简体   繁体   English

尝试使用jQuery动态验证字段 - 自定义函数

[英]Trying to dynamically validate fields with jQuery - custom function

I'm working on a validation function in jQuery and am getting a bit stuck. 我正在研究jQuery中的验证函数,并且有点卡住了。 I've got a working version that is very lengthy and full of hardcoded form values which I'm trying to avoid. 我有一个非常冗长且充满硬编码形式值的工作版本,我正在努力避免。 Here's what works, currently: 这是有效的,目前:

$(document).ready(function(){
  var fname = $("#formFName");
  var lname = $("#formLName");

  fname.blur(validateFName);
  lname.blur(validateLName);

  function validateFName(){
    if(fname.val().length > 0){
      fname.removeClass("req_error");
      return true;
    }
    else {
      fname.addClass("req_error");
      return false;
    }
  }

  function validateLName(){
    if(lname.val().length > 0){
      lname.removeClass("req_error");
      return true;
    }
    else {
      lname.addClass("req_error");
      return false;
    }
  }
});

That part works fine for those two fields but I'd like to encapsulate the whole thing in a function that's a bit easier to maintain. 那部分适用于这两个字段,但我想将整个事件封装在一个更容易维护的函数中。 Something like this: 像这样的东西:

$(document).ready(function(){

  $("#first_name").blur(validateField("first_name","text"));
  $("#last_name").blur(validateField("last_name","text"));
  $("#email_address").blur(validateField("email_address","email"));

  function validateField(formfield, type){
    var field = $("#" + formfield);
    switch(type) {
      case "text":
        if(field.val().length > 0){
          field.removeClass("req_error");
          return true;
        }
        else {
          field.addClass("req_error");
          return false;
        }
        break;
      case "email":
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        if(filter.test(field.val())) {
          field.removeClass("req_error");
          return true;
        else {
          field.addClass("req_error");
          return false;
        }
        break;
    }
  }
});

However, when I do that I get the following error in Firefox's JS error log: 但是,当我这样做时,我在Firefox的JS错误日志中收到以下错误:

Error: ((f.event.special[r.origType] || {}).handle || r.handler).apply is not a function Source File: /scripts/jquery-1.7.1.min.js Line: 3 错误:((f.event.special [r.origType] || {})。handle || r.handler).apply不是函数源文件:/scripts/jquery-1.7.1.min.js行: 3

A quick Google for that error hasn't yielded anything that means anything to me, unfortunately. 不幸的是,一个快速谷歌的错误并没有给我带来任何意义。 I've tried alerts in various spots and doing so has verified that the proper form field names are indeed being passed where there supposed to be, but as I'm fairly new to jQuery (and not great at JavaScript) I'm at a bit of a loss here. 我已经尝试了各种各样的警报,并且这样做已经证实正确的表单字段名称确实正在传递到应该存在的地方,但是因为我对jQuery很新(并且在JavaScript上不是很好)我在这里有点不知所措。

Thanks to anyone who can point me in the right direction. 感谢任何能指出我正确方向的人。 Also, if anyone thinks that I'm going about this in the wrong way, I'm more than happy to change. 此外,如果有人认为我以错误的方式解决这个问题,我很乐意改变。 I tried using the jQuery validation plugin but I'm also using some dynamically created fields and unfortunately the plugin prevents the visitor from submitting the form when hidden required fields are involved. 我尝试使用jQuery验证插件,但我也使用了一些动态创建的字段,不幸的是,当涉及隐藏的必填字段时,插件会阻止访问者提交表单。

Sounds like you could simplify this by attaching behavior instead of specific elements: 听起来你可以通过附加行为而不是特定元素来简化这一点:

<input type="text" id="someId" class="validate-text" />
<input type="text" id="someOtherId" class="validate-email" />

$('.validate-text').live('blur', function()
{
    $(this).removeClass('req_error');
    if($.trim(this.value).length < 1)
       $(this).addClass('req_error');
});

$('.validate-email').live('blur', function()
{
    // Same thing with the email validation logic
});

This way, you dont need to attach specific event handlers to your elements and instead use those handlers to check the behavior you want. 这样,您不需要将特定事件处理程序附加到元素,而是使用这些处理程序来检查所需的行为。 Then you simply mark HTML elements with specific classes to mark the validation mode you want. 然后,您只需使用特定类标记HTML元素即可标记所需的验证模式。

Assuming I understood your question correctly. 假设我正确地理解了你的问题。

You can't pass a function invocation expression to .blur(). 您不能将函数调用表达式传递给.blur()。 You can pass an anonymous function constructor: 您可以传递一个匿名函数构造函数:

$("#first_name").blur(function () {validateField("first_name","text");});

Or pass the name of a function: 或传递函数的名称:

function validateFirstName() {
    validateField("first_name","text");
}

* * *

$("#first_name").blur(validateFirstName));

@Tejs's suggestion to use classes to attach validators is a good one, as well. @ Tejs建议使用类来附加验证器也是一个很好的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM