如何检查 HTML 标记,然后在 jQuery 验证中添加错误

how to check for HTML tags and then add error in jQuery Validation

本文关键字:jQuery 然后 验证 错误 添加 标记 何检查 检查 HTML      更新时间:2023-09-26

我正在尝试使用jQuery验证插件验证我的表单。

这是代码

    $(document).ready(function(){
        var productsForm=$('#products-form');
     productsForm.validate({
            //debug:true,
          invalidHandler: function(event, validator) {
    // 'this' refers to the form
    var errors = validator.numberOfInvalids();
    if (errors) {
    var message = errors == 1
    ? 'You missed 1 field. It has been highlighted'
    : 'You missed ' + errors + ' fields. They have been highlighted';
    $("div.error span").html(message);
    $("div.error").show();
    } else {
    $("div.error").hide();
    }
    },
         rules:{
             productName: {
                 required: true,
                 minlength:2,
//here i tried to create a function
                 onfocusout: function(element){
                 var myValue=$(element).val();
                 if(myValue.match(/[<>$]/))
                 {
                     alert('Please enter the Name without any tags.');
                     $(element).valid=false;
                 }
             }
             },
             productType: {
                 required: true,
                 minlength:2,
             },
             productBrand: {
                 required: true,
                 minlength:2,
             },
             description: {
                 required: true,
                 minlength:10,
                 maxlength:150,
             },
             updatedBy:{
                 required:true,
                 minlength:2,
             }
         },
         messages:{
             productName:{
                 required: "Please enter the productName",
                 minLength: "The name should be atleast 2 characters long",
             },
             productType: {
                 required: "Please enter the productType",
                 minlength:"The type should be atleast 2 characters long",
             },
             productBrand: {
                 required: "Please enter the productBrand",
                 minlength:"The Brand Name should be atleast 2 characters long",
             },
             description: {
                 required: "Please describe your product",
                 minlength: "The description should be atleast 10 characters long",
                 maxlength: "You can not enter more than 150 characters",
             },
             updatedBy:{
                 required: "PLease Your name",
                 minlength: "The name should be atleast 2 characters long",
             }
         },
         submitHandler: function(form){
             if(productsForm.valid())
             {
                alert('tada');
                 return false;
             }
             else
             {
                 alert('not valid');
                 return false;
             }
         }
     });   
    });

现在我正在尝试创建一个函数来检查输入值是否包含 HTML 标签。 如果是,则显示错误 msg 并且不提交表单。但我不知道该怎么做。谁能帮忙?

我尝试创建一个函数作为onfocusout但不知道如何添加错误。

引用标题:

"如何检查 HTML 标记,然后在 jQuery 验证中添加错误"

如果您使用的是 jQuery 验证插件,则只需为字段指定规则,相应的错误消息就会自动切换。 有用于创建自定义规则的内置方法,也有用于用自定义文本重写任何错误文本的内置方法。 该插件会在任何错误(包括自定义规则触发的错误)期间自动阻止表单提交。

引用 OP:

"现在我正在尝试创建一个函数来检查输入是否 值是否包含 HTML 标记。如果是,则显示错误 msg 和 不要提交表格。

您的第二句话只是描述了每个验证规则的作用。 检查输入数据并在此测试失败时阻止提交。 你的第一句话就是你希望你的规则做什么......确保输入不包含标记。

引用 OP:

"我试图创建一个函数作为onfocusout但不知道如何添加错误。

您的代码尝试表明您正在使这种方式比需要的更复杂。 您无需修改插件的任何单个回调函数即可创建一个新规则......在这一点上,您不妨从头开始编写自己的验证插件。

要实现您想要的,您只需要使用 addMethod 方法来编写自己的自定义 jQuery 验证规则。 在这种情况下,您需要一个将排除 HTML 标记的正则表达式...也许只允许字母和数字。 (调整正则表达式或用您认为合适的任何功能替换函数)。

请参考这个非常基本的例子:

jQuery.validator.addMethod("noHTML", function(value, element) {
    // return true - means the field passed validation
    // return false - means the field failed validation and it triggers the error
    return this.optional(element) || /^([a-z0-9]+)$/.test(value);
}, "No HTML tags are allowed!");
$('#myform').validate({
    rules: {
        field1: {
            required: true,
            noHTML: true
        }
    }        
});

演示:http://jsfiddle.net/mM2JF/


但是,additional-methods.js文件已经包含各种规则,这些规则会自动排除任何 HTML...

letterswithbasicpunc => "请仅使用字母或标点符号"

alphanumeric => "字母、数字和下划线只请"

lettersonly => "请只写信"


$('#myform').validate({
    rules: {
        field1: {
            required: true,
            alphanumeric: true  // <- will also not allow HTML
        }
    }        
});

演示 2:http://jsfiddle.net/mM2JF/1/

尝试使用此代码来验证 HTML 标记

jQuery.validator.addMethod("noHTMLtags", function(value, element){
    if(this.optional(element) || /<'/?[^>]+(>|$)/g.test(value)){
        return false;
    } else {
        return true;
    }
}, "HTML tags are Not allowed.");

$('#form').validate({
rules: {
    message: {
        required: true , noHTMLtags: true
    }
}});

我希望这也是一个很好的例子。

这是我所做的事情的例子

$.validator.addMethod("CHECKDOB", function(value, element) {  
            return this.optional(element) || check_blank_dob(element); 
            }, "Please Enter Birth Date");

//参见 checkdob 函数已添加到验证器

现在

在规则中

 rules:{
                        <%=txtfirstname.UniqueID %>: {required: true},                            <%=txtlastname.UniqueID %>: {required: true},
                        <%=txtdateofbirth.UniqueID %>: {                            required: true,
                        CHECKDOB:"Please Enter Birth Date",//see here i have called that function
                        date:true                  
                        },

现在消息

messages: {
         <%=txtfirstname.UniqueID %>:{required: "Please Enter First Name"},
        <%=txtlastname.UniqueID %>:{required: "Please Enter Last Name"},
         <%=txtdateofbirth.UniqueID %>:{
          required: "Please Enter Birth Date",
          CHECKDOB:"Please Enter Birth Date",
          date:"Invalid Date! Please try again" 
                        },

这是你的函数

 function check_blank_dob()
    {
       var birth=document.getElementById("<%=txtdateofbirth.ClientID%>").value
       if(birth=="__/__/____")
       {
                return false;
       }
            return true;
    }

看到我在将方法添加到验证器时在checkdob函数中调用的这个函数

这只是如何添加您必须实现您的方法的示例,我希望这会对您有所帮助..:)

我使用正则表达式来防止文本区域中的 HTML 标记

$.validator.addMethod(
    "no_html",
    function(value, element) {
        if(/<(.|'n)*?>/g.test( value )){
            return false;
        }else{
            return true;
        }
    },
    "HTML tag is not allow."
);
$('#myform').validate({
    rules: {
        field1: {
            required: true,
            no_html: true
        }
    }        
});