Can Parsley.js work without form element?

余生长醉 提交于 2020-01-02 02:54:07

问题


<form id="f">
    <div class="form-group">
        <label for="exampleInputEmail1">Email address</label>
        <input parsley-type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" parsley-trigger="keyup">
    </div>
 </form>
<script>
    $(function(){
        $('#f').parsley('validate');
    });
</script>

Instead of form element I would like to validate content in div element, is it possible?


回答1:


Parsley just cannot validate the text inside a div / span element. But you could perfectly validate an input not inside a form tag, in your example you could just do $('#exampleInputEmail1').parsley('validate');




回答2:


I've been able to (ab)use the excellent Parsley validator for non-input elements like so,

var inputField = $J('<input id="someRandomID" type="text" data-parsley-type="alphanum" data-parsley-required="true" >');
var parsleyHandle = inputField.parsley();
inputField.val('wronginput!@#!#!@#');
console.log(parsleyHandle.isValid()); // should be false

inputField.val('correctinput');
console.log(parsleyHandle.isValid()); // should be true

Obviously, source of the value could be anything - a div, a span, etc.

Best of luck




回答3:


I had a similar issue. In SharePoint 2013 (in a Visual Web Part at least) adding a form directly in the markup causes grief. SP will 'formify' it by adding a huge blob of generated markup and change the look and feel. While there is likely a way to remedy that issue, I wanted to quickly add Parsley to a table with many inputs without toying with the SP-generated form. My solution was to use jQuery $.wrap() after the UI was rendered. Works like a charm. Yes, it still uses a form element, but maybe you were avoiding a form for similar reasons. Try this JSFiddle

<div id='container'>
  <button type="button" id="save">Save</button>
  <table>
    <tr>
        <td><input type='number' min='0' max='999' /></td>
        ... many more inputs
   </tr>
   ...
  </table>
</div>
<script ... >
$(document).ready(function(){

     $("#container").wrap("<form id='fooForm'></form>");

     var options = {
         uiEnabled: true,
         errorsWrapper: '',
         excluded: '.inActive'
     };

     // create the validator
     $("#fooForm").parsley(options);

     // wire up click event for the save button
     $("#save").click(function () {

         // react to form valid state
         // calling parsley again only returns the
         // ref to the original, does not duplicate
         var validator = $("#fooForm").parsley();

         validator.validate();

         // handle validator.isValid();           
         // ajax form post or other

     });
});

</script>


来源:https://stackoverflow.com/questions/21884016/can-parsley-js-work-without-form-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!