jquerysharepoint-2010jquery-validate

jQuery Validator Plugin: Validate contents of a div


In a SharePoint 2010 form, a Rich Text field is rendered not as a form element, but as a div. I need to use jQuery Validator Plugin to check the contents of this div.

<form>

  <!-- this will validate -->
  <select class="check_this">
    <option>Testing form element</option>
  </select>

  <!-- this will not validate -->
  <div class="check_this">
    Testing div
  </div>

</form>

Solution

  • The problem is that non-form elements are not tested against, right?

    I haven't tested this approach but why don't you render an empty select-element that has the same name as the id of div and add a method that grabs the correct element:

    HTML:

    <form>
        <!-- this is a dummy element -->
        <select name="myElem">
            <option>Testing form element</option>
        </select>
    
        <!-- this is my actual element -->
        <div id="myElem">
            Testing div
        </div>
    </form>
    

    JS:

    jQuery.validator.addMethod("myForm", function(value, element) { 
        var strId = $(element).attr('name');
        var myActualElement = $('form').find('#' + strId);
        var myActualContent = myActualElement.text();
    
        return this.optional(element) || /regexwhateveryouwant/.test(myActualContent); 
    }, "Custom error message");
    

    If you're not able to render a dummy select-element, you need to create it with jQuery.