inside
inside

Reputation: 3177

Send AJAX request only if form validation successfull in Polymer

I am using Polymer 1.0 iron-form to get user input and send AJAX request to the server with iron-ajax:

     <form is="iron-form" id="form" >
      <paper-input name="userEmail" label="Email" required></paper-input>
      <paper-input name="password" type="password" label="Password" required></paper-input>
      <br>
      <paper-button raised
          on-click="login">Submit</paper-button>
    </form>

<script>
  (function() {
    Polymer({
        is: 'module-login',
        login: function() {
            // this is used to trigger Polymer's form validation
            Polymer.dom(event).localTarget.parentElement.submit();

            // this is my ajax request
            this.$.auth.login(this.$.userEmail.value, this.$.password.value);
        }
    });
 })();
</script>

where Polymer.dom(event).localTarget.parentElement.submit(); is used to validate the form for required input.

So what I am trying to achieve is to send AJAX request only if form validation was successful, but at this point even if form will show errors it will still proceed to the AJAX request.

I probably need to put validation and the actual AJAX request into two different calls but I am a bit stuck.

Upvotes: 1

Views: 692

Answers (1)

Jakemmarsh
Jakemmarsh

Reputation: 4671

I don't think Polymer.dom(event).localTarget.parentElement.submit(); runs any validation, that literally just submits the form. See here.

The actual method you should be using, as seen in that link, is .validate(). This will return a boolean, meaning you can then wrap the actual login call in an if statement:

if ( Polymer.dom(event).localTarget.parentElement.validate() ) {
   this.$.auth.login(this.$.userEmail.value, this.$.password.value);
}

Upvotes: 1

Related Questions