[SOLVED] Username and e-mail remote validation at client side?

Hi, at the Create User form, submitting with an already existing user name or email returns an error requesting to change them for ones that are not used. I would like to know if it’s possible to validate on the client side and show an error without submitting the form.

While browsing I found the JQuery Validation supports a remote rule which requests the server with the data and it receives a true/false response in whether the data already exists:

validator = $('#emailForm').validate({
    rules: {
        newEmail: {
            required: true,
            remote: {
                url: '/rest/checkDupEmail',
                data: { email: $('#newEmail').val()},
                dataFilter: function(data) {
                    var json = JSON.parse(data);
                    console.log($('#newEmail').val());
                    console.log(data);
               }
            }
        }
    }
});

(code source: https://stackoverflow.com/questions/27573916/jquery-remote-validation-passing-extra-parameter)

You can obviously change that if you want to, but you will need to create the AJAX request yourself as well as the route that is called by the AJAX request.

1 Like

Originally I was looking for some YAML syntax to add the remote rule, but later I found I could solve this by using Javascript code to add a new rule to the input control, in a new asset file:

$(function() {
    $('input[name="user_name"]').rules("add", {
        remote: {
            url: "/user-exists"
        },
        messages: {
            remote: "Username is in use!"
        }
    });

    $('input[name="email"]').rules("add", {
        remote: {
            url: "/user-exists"
        },
        messages: {
            remote: "Email is in use!"
        }
    });
});

The /user-exists route is mapped to the controller method where I check if either user_name or email exists in the users table.

(source, for rules addition: https://stackoverflow.com/questions/3033910/jquery-how-to-dynamically-add-a-validation-rule)

Thanks for the help!