Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing form submission after validation by parsley.js

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

However, every time I submit the form the page refreshes. preventDefault seems 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?

<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>
like image 783
morty Avatar asked Sep 21 '14 11:09

morty


1 Answers

if you are using parsely 2 you can try this

$(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 documentation check Form with examples and events

like image 193
ahmed gdoma Avatar answered Sep 28 '22 04:09

ahmed gdoma