Parsley.js Trigger Error on AJAX

荒凉一梦 提交于 2019-12-07 18:08:28

问题


I am using parsley.js for client-side validation. I have a field called username, which must be unique. The field looks like this:

<input type="text" name="loginUsername" id="loginUsername" class="form-control" placeholder="Username" data-minlength="2" data-maxlength="40" data-required="true">

This is my ajax function:

function validateField(field)
{
    var isValid = $( '#'+field ).parsley( 'validate' );
    if (!isValid) return false;
    return true;
}

$( '#regUsername' ).blur(function(){
    if (!validateField('regUsername')) return false;
    var username = $(this).val();
    $.post('<?= SITE_ROOT; ?>/ajax/ajaxUserActions.php',
    {
        data: 'checkUniqueUsername',
        username: username
    }, 'json')
    .done(function(data){            
        if (data.error)
        {                
        }            
    })
    .fail(function(){ $( '#loader' ).hide(); });
});

If the is an error I would like to trigger a parsley error and then show a custom message. Does anyone know how to do this. I am thinking something like this:

$('#regUsername').attr('data-error-message', 'Username Taken').trigger('parsley-error');

I am not sure, any help would be greatly appreciated.


回答1:


Is there a reason why you don't want to use a custom validator? I think it is more clear if you define a new custom validator when parsley is applied to your form.

This is how I do it: In your input add "parsley-username":

<input type="text" name="loginUsername" id="loginUsername" class="form-control"
    placeholder="Username" data-required="true" parsley-username >

When you bind parsley to your form, you should define a new custom validator named "username", like this:

<script type="text/javascript">
$( '#form' ).parsley( {
    validators: {
      username: function() {
            return {
                validate: function(val) {
                    var response = false;

                    $.ajax({
                        url: SITE_ROOT +  "ajax/ajaxUserActions.php",
                        data: {'username': val, 'data': 'checkUniqueUsername'},
                        dataType: 'json',
                        type: 'get',
                        async: false,
                        success: function(data) {
                            if (data.total > 0)
                                response = false;
                            else
                                response = true;
                        },
                        error: function() {
                            response = false;
                        }
                    });

                    return response;
                },
                priority: 32
            }
        }
    }
  , messages: {
      username: "Your username is already taken. Please insert other value"
    }
} );
</script>

A few things you should be aware:

  1. In your example, you define your URL using a PHP constant. In my code, I assume you have a javascrip variable named SITE_ROOT with the same value as the php variable. If you insert this code inside a php file, it will work with your constant (although, I do not recomend using this code inside php. It will be more clear inside a javascript file).

  2. The ajax request must have async defined to false. This way, the rest of the code must wait for the ajax to be completed.

  3. My code assumes that your AJAX will echo a JSON object with a property called "total". It total = 0, the username is not taken.

This code works with parsley 1.*

Update for Parsley 2.*

As of Parsley 2.0, the input will have the following attributes:

<input type="text" name="loginUsername" id="loginUsername" class="form-control"
    placeholder="Username" data-parsley-required data-parsley-username >

And you now must bind the validator like this:

<script type="text/javascript">
    window.ParsleyValidator
        .addValidator('username', function (value, requirement) {
             var response = false;

               // Your code to perform the ajax, like before

                return response;
        }, 32)
        .addMessage('en', 'username', 'Your username is already taken.');
</script>

Another possibility is to use the built in remote ajax validator (see the docs)



来源:https://stackoverflow.com/questions/20402750/parsley-js-trigger-error-on-ajax

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