www.webdeveloper.com
Results 1 to 2 of 2

Thread: JQuery Validation rules addMethod question

  1. #1
    Join Date
    Feb 2011
    Posts
    2

    JQuery Validation rules addMethod question

    I have created a php filter for a form that returns an error message if someone uses profanity in the comments field and makes them redo that field before inserting into a database. Here is the code I use for that (I have omitted the lengthy list of profanity..):

    Code:
    if (isset($_POST['comments'])){
    
    $comments = $_POST['comments'];
    
    $filter=array("badword1", "badword2");
    for ($i = 0; $i < count($filter); $i++) {
    
    if (preg_match("/\b".$filter[$i]."\b/i", $comments)) {
    
    $profanity_msg="Profanity is not allowed";
           }
       }
    }
    //Then this before the form
    if(isset($profanity_msg)){
    echo $profanity_msg;
    }
    However, the rest of my form is validated through JQuery Validator and I would like to make a rule that would do the filtering instead of relying on the php. Here is a sketch of what I think I will need to do to build the custom rule, but I am not sure how to write the equivalent function to my php code above. Any help would be appreciated...
    Code:
    $(document).ready(function(){
    //custom validation rule - profanity
    $.validator.addMethod("profanity",
    
    "Equivalent of my php function goes here..."
    
    );
    
    //validation implementation will go here.
    $("#TestForm").validate({
    rules: {
    comments: {
    required: true,
    profanity: true
    }
    },
    messages: {
    comments: {
    required: "* Required",
    profanity: "* No Profanity Allowed"
    }
    }
    });
    })

  2. #2
    Join Date
    Feb 2011
    Posts
    2
    I pieced together the code below and it works for only the first word. Any suggestions would be appreciated.

    Code:
     $(document).ready(function(){
         //custom validation rule - profanity
     $.validator.addMethod("profanity",  function(value, element)
    
      {
    
    var filter = ['bad', 'word'];
    
    var i=0;
    for (i=0;i<=filter.length;i++)
    	{
         return !RegExp('\\b' + filter[i] + '\\b', 'gi').test(value);
    	}
    
      }
    
     );

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles