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

标签 javascript jquery jquery-validate

我正在尝试使用 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 标记。如果是,则显示错误消息并且不提交表单。但我不知道该怎么做。有人可以帮忙吗?

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

最佳答案

引用标题:

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

如果您使用 jQuery Validate 插件,则只需为字段指定规则,相应的错误消息就会自动切换。有用于创建自定义规则的内置方法和用于使用自定义文本覆盖任何错误文本的内置方法。该插件会在出现任何错误(包括自定义规则触发的错误)时自动阻止表单提交。

引用OP:

"Now I am trying to create a function which checks whether the input values contain html tags or not. If yes then show the error msg and do not submit the form."

您的第二句话仅描述了每个验证规则的作用。检查输入数据并在测试失败时阻止提交。您的第一句话是您希望规则执行的操作...确保输入不包含标签。

引用OP:

"I tried to create a function as onfocusout but do not know how to add error."

您的代码尝试表明您使这种方式变得比实际需要的更加复杂。您不需要仅仅为了创建一个新规则而修改插件的任何单个回调函数...此时您不妨从头开始编写自己的验证插件。

要实现您想要的效果,您只需使用 the addMethod method编写您自己的自定义 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/

<小时/>

但是,the additional-methods.js file已经包含各种规则,可以自动排除任何 HTML...

letterswithbasicpunc =>“请仅输入字母或标点符号”

字母数字 =>“请仅包含字母、数字和下划线”

仅字母 =>“请仅字母”

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

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

关于javascript - 如何检查 HTML 标签,然后在 jQuery 验证中添加错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20651382/

相关文章:

javascript - RegExp 等价于 array.indexOf( str )

javascript - 如何仅在JQuery上的指定区域更改类?

jquery - 添加 css 类验证规则时如何分配错误消息

jquery - 在 jQuery 中选择当前元素

javascript - Jquery 验证不起作用返回有效结果

jQuery 验证正则表达式以禁止数字和特殊字符

javascript - react 路由器开关未按预期工作

javascript - 无法从子组件更新状态

javascript - 将 JSON 解析为 HTML 嵌套列表

javascript - 为什么不将全局变量值传递给函数?