如何检查HTML标记,然后在jQuery验证中添加错误 [英] how to check for HTML tags and then add error in jQuery Validation

查看:117
本文介绍了如何检查HTML标记,然后在jQuery验证中添加错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery Validation插件来验证我的表单.

这是代码

    $(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,但不知道如何添加错误.

解决方案

引用标题:

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

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

引用OP:

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

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

引用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/

I am trying to validate my form using jQuery Validation plugin.

Here is the code

    $(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;
             }
         }
     });   
    });

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. But I do not know how to do that. Can anyone help please?

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

解决方案

Quote Title:

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

If you're using the jQuery Validate plugin, you only need to specify a rule for a field and the corresponding error message is toggled automatically. There are built-in methods for creating custom rules and built-in methods for over-riding any error text with your custom text. The plugin automatically blocks the form submission during any error including errors triggered from your custom rules.

Quote 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."

Your second sentence merely describes what every single validation rule does. Checks the input data and blocks submission on failure of this test. Your first sentence is what you want your rule to do... make sure the input contains no tags.

Quote OP:

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

Your code attempt indicates that you're making this way way more complicated than it needs to be. You do not need to tinker with any single callback function of the plugin just to create one new rule... at that point you might as well write your own validation plugin from scratch.

To achieve what you want, you simply need to use the addMethod method to write your own custom jQuery Validation rule. In this case, you'll need a regex that will exclude HTML tags... perhaps by only allowing letters and numbers. (Tweak the regex or replace the function with anything you see fit).

Refer to this really basic example:

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
        }
    }        
});

DEMO: http://jsfiddle.net/mM2JF/


However, the additional-methods.js file already includes various rules that would automatically exclude any HTML...

letterswithbasicpunc => "Letters or punctuation only please"

alphanumeric => "Letters, numbers, and underscores only please"

lettersonly => "Letters only please"


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

DEMO 2: http://jsfiddle.net/mM2JF/1/

这篇关于如何检查HTML标记,然后在jQuery验证中添加错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆