Javascript 防止通过 parsley.js 验证后提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25958507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:08:33  来源:igfitidea点击:

Preventing form submission after validation by parsley.js

javascriptparsley.js

提问by morty

I have used parsley.js many times and have literally copied the code from my last use of parsley.

我已经多次使用 parsley.js 并且从我上次使用 parsley 的时候复制了代码。

However, every time I submit the form the page refreshes. preventDefaultseems to work on my other pages and stops the page from refreshing but for some reason when I tried now it won't work. Can anyone figure out why not?

但是,每次我提交表单时,页面都会刷新。preventDefault似乎在我的其他页面上工作并阻止页面刷新,但由于某种原因,当我现在尝试时它不起作用。谁能弄清楚为什么不?

<script>
    $(function(){
        $("#register_signup").submit(function(e){
            e.preventDefault();
            var form = $(this);
            if ($('#rform').parsley( 'isValid' )){
                alert('valid');
            }
        });
    });
</script>

<form id='rform' name='rform' data-parsley-validate>
    <input id='reg_password' class='register_input' type='text'  autocomplete="off" data-parsley-trigger="change" placeholder='Password' required>
    <input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword" placeholder='Confirm password' data-parsley-equalto="#reg_password" required>

    <input id='register_signup' type="submit" onClick="javascript:$('#rform').parsley( 'validate' );" value='Sign Up' />
</form>

回答by Luís Cruz

You are binding the submitevent to a inputelement. If you check the jquery $.submit() documentation, it states that:

您正在将submit事件绑定到一个input元素。如果您查看jquery $.submit() 文档,它会指出:

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form>elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.

当用户尝试提交表单时,将提交事件发送到元素。它只能附加到<form>元素上。可以通过单击明确的<input type="submit"><input type="image"><button type="submit">或在某些表单元素具有焦点时按 Enter来提交表单。

This is your main problem and this is why alertwill never be displayed (in fact, that code is never executed).

这是您的主要问题,这就是为什么alert永远不会显示的原因(实际上,该代码永远不会执行)。

I would also change a few things:

我也会改变一些事情:

  1. $('#rform').parsley( 'validate' )should be $('#rform').parsley().validate(), assuming you are using Parsley 2.*
  2. $('#rform').parsley( 'isValid' )should be $('#rform').parsley().isValid().
  3. Use $.on()instead of $.submit().
  4. Remove onClickfrom the register_signupelement. Since you are already using javascript, I would do this directly in the javascript code instead of onclick. This is more a personal preference.
  1. $('#rform').parsley( 'validate' )应该是$('#rform').parsley().validate(),假设您使用的是 Parsley 2.*
  2. $('#rform').parsley( 'isValid' )应该是$('#rform').parsley().isValid()
  3. 使用$.on()代替$.submit()
  4. onClickregister_signup元素中删除。由于您已经在使用 javascript,我会直接在 javascript 代码中而不是 onclick 中执行此操作。这更多是个人喜好。

So, your code will be something like this:

所以,你的代码将是这样的:

<form id='rform' name='rform'>
    <input id='reg_password' class='register_input' type='text'  autocomplete="off" 
        data-parsley-trigger="change" placeholder='Password' required>
    <input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword"
         placeholder='Confirm password' data-parsley-equalto="#reg_password" required>

    <input id='register_signup' type="submit" value='Sign Up' />
</form>

<script>
    $(document).ready(function() {
        $("#rform").on('submit', function(e){
            e.preventDefault();
            var form = $(this);

            form.parsley().validate();

            if (form.parsley().isValid()){
                alert('valid');
            }
        });
    });
</script>

回答by Safoor Safdar

When you apply data-parsley-validate to your form, you don't need to apply javascript to form to stop submit until all validation run. But if you applying javascript return false when parsely() not valid. And just make sure you have include parsley.js code file.

当您将 data-parsley-validate 应用于表单时,您不需要将 javascript 应用于表单以停止提交,直到所有验证运行。但是,如果您在 parsely() 无效时应用 javascript 返回 false。并确保您有包含 parsley.js 代码文件。

回答by ahmed gdoma

if you are using parsely 2 you can try this

如果你使用的是 parsely 2 你可以试试这个

$(function () {
//parsely event to validate form -> form:valiate
$('#rform').parsley().on('form:validate', function (formInstance) {
    //whenValid return promise if success enter then function if failed enter catch
    var ok = formInstance.whenValid()
    //on success validation
    .then(function(){
        alert('v');
        formInstance.reset();
    })
    //on failure validation
    .catch(function(){
        formInstance.destroy();
    });

$('.invalid-form-error-message')
  .html(ok ? '' : 'You must correctly fill *at least one of these two blocks!')
  .toggleClass('filled', !ok);
  // console.log(formInstance);
if (!ok)
  formInstance.validationResult = false;
  console.log(formInstance);
});

//parsely event to submit form -> form:submit
$('#rform').parsley().on('form:submit', function (formInstance) {
// if you want to prevent submit in any condition after validation success -> return it false
return false;
});

//default submit still implemented but replaced with event form:submit
$('#rform').submit(function () {
  alert('dd');
});
});

for more details parsely documentationcheck Form with examples and events

有关更多详细信息,请查看带有示例和事件的文档检查表单