how to check for HTML tags and then add error in j

2020-08-05 10:15发布

问题:

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.

回答1:

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/



回答2:

Try this Code to Validate the HTML tags

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

I Hope this is also a good example.



回答3:

Here is the exmple of what i hve done

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

//See checkdob function is added to validator

Now

In rules

 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                  
                        },

now messages

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" 
                        },

Here is your function

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

See this function i have called at checkdob function when adding method to validator

This is just the example how to add you have to implement your method i hope this will help you regards....:)



回答4:

I use regular expression for preventing HTML tags in my textarea

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