0

I came across a problem with Jquery validate when trying to ensure that a user's email address is unique. I'm trying to validate a user details update form. Now, the email and username are unique, so when I try to validate it with Jquery validate's remote rule, it only sends the value entered, and the server side code tells it that it's in fact taken, even though it's taken by the same user. So, my question is: is there some kind of way to prevent this through jquery validate? Like, maybe some kind of data-original-value attribute of some sort, OR alternatively, is there any way to get it to send additional data with the ajax request, so that I can then use it on the server side code to check whether the value is taken by the same user or not?

Here's my code. It's fairly standard:

$(".validateForm").validate({
    rules: 
    {
        handle: 
        {
            required: true,
            remote:'/home/check'
        }
    },
    messages: 
    {
        handle: 
        {
            required: "Must include a handle",
            remote:"This handle is already used up. Please, choose another one."
        }
    }
});
Sparky
  • 98,165
  • 25
  • 199
  • 285
Northern
  • 113
  • 7

1 Answers1

0

...is there some kind of way to prevent this through jquery validate?

No.

There is no intelligence to the remote method... it simply validates as per what you send it from the server. In other words, your server-side code at /home/check must figure out whether the field is valid and send back the appropriate response.

Shouldn't your server-side code be smart enough to know whether you're dealing with a new user or an existing user that's already logged in and editing their account? After all, solely relying on client-side code means that anyone could potentially defeat this by simply disabling or altering the JavaScript.

...OR alternatively, is there any way to get it to send additional data with the ajax request

Yes.

Reading the docs:

...[for] options to fully customize the request, see jQuery.ajax for details

So as per the example in the docs, you could use the data option from $.ajax like this...

rules: {
    handle: {
        required: true,
        remote: {
            url: '/home/check',
            data: {
                more_stuff: function() {
                    return "some_value";
                }
            }
        }
    }
}

Note that the value of the field being validated is still being sent along with this.


Sidenote: you may wish to reconsider using Allman code formatting for your JavaScript.

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285