简体   繁体   English

触发欧芹验证没有提交表格?

[英]Trigger parsley validation without submit form?

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 ? 所以我的问题是,如果有一种方法可以在不添加提交按钮的情况下触发欧芹验证?

$form.parsley('validate') is 1.x API. $form.parsley('validate')是1.x API。 It was deprecated in 2.x versions you might use. 它在您可能使用的2.x版本中已弃用。

Try $form.parsley().validate() instead. 请尝试使用$form.parsley().validate()

Best 最好

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. 正如旁注,在div标签上使用data-parsley-validate属性也可以。 You can also initialise the form as normal (meaning you can subscribe to the validation). 您也可以正常初始化表单(这意味着您可以订阅验证)。

example html: 示例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: 只需确保将js放入:

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

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

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

如果你在按钮上放置type =“button”,它将不会刷新并在单击时滚动到页面顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM