Trigger parsley validation without submit form?

柔情痞子 提交于 2019-12-18 12:53:15

问题


Given this code, it never works and always returns true whatsoever ?

<form id="my-form" data-validate="parsley">
  <p>
    <label for="username">Username * :</label>
    <input type="text" id="username" name="username" data-required="true" >
  </p>

  <p>
    <label for="email">Email Address * :</label>
    <input type="text" id="email" name="email" data-required="true" >
  </p>

  <br/>

  <!-- Validate all the form fields by clicking this button -->
  <a class="btn btn-danger" id="validate" >Validate All</a>
</form>

<script>
var $form = $('#my-form');
$('#validate').click (function () {
    if ( $form.parsley('validate') )
      console.log ( 'valid' ); <-- always goes here
    else
      console.log ('invalid');
});

</script>

So my question is if there is a way to trigger parsley validation without adding a submit button ?


回答1:


$form.parsley('validate') is 1.x API. It was deprecated in 2.x versions you might use.

Try $form.parsley().validate() instead.

Best




回答2:


I've been searching high and low to try and make the form validation work with a non-form tag. I guess my biggest gripe with the framework is that it doesn't work out-of-the-box with non-form elements. I would be ok using a form element if it didn't scroll to the top of the page every time it tries to validate. Because this behavior is inherent in how form works, there is only this hack to fix it.

Just as a side note, using data-parsley-validate attribute on the div tag also works. You can also initialise the form as normal (meaning you can subscribe to the validation).

example html:

<div id="signupForm" data-parsley-validate>
    ... put form inputs here ...
    <button id="signupBtn">Sign me up</button>
</div>

Just make sure to put js in:

var $selector = $('#signupForm'),
    form = $selector.parsley();

form.subscribe('parsley:form:success', function (e) {
    ...
});

$selector.find('button').click(function () {
    form.validate();
});



回答3:


if you put type="button" on the button, it won't refresh and scroll to top of page when clicked.



来源:https://stackoverflow.com/questions/22781490/trigger-parsley-validation-without-submit-form

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