js-防止表单提交

I got a form submitted by a button type="submit",when i click it , it start the frontend validation but i also have some server validation that i have to do with ajax. For example that the name it's not used by another person.

My problem is that if i change to button type="button" the frontend validation don't execute. Only the ajax validation do it. What can i do? P/D: i use tiny.js that is similar to jquery for js events.

html

<form>
  <input name="name" class="name">
  <button type="submit" class="name__valid" value="save">save</button>
<form>

js

tiny.ajax("/update",
    {
        method: "PUT",
        data: {
            name: document.querySelector('name__valid').value;
        },
        dataType: "json",
        success: function (data) {
            alert('available name');
            window.location = "/home?name-update=success"
        },
        error: function (error) {
            //example: used name error
            var errorJSON = JSON.parse(error.response);

            console.log('Messages ' + errorJSON.messages);
        }
    }
);

//this validation only it's executed by de button (type submit)
var name = new ch.Validation(ch('.name__valid')[0], {
    'conditions': [{
        'name': 'invalid-name',
        'message': 'this name it's not valid'
    }]
});

You want to use event.preventDefault when the form is submitted.

document.querySelector('form').onsubmit = function(e) {
  e.preventDefault();
  // Do your Ajax request after.
}

On JSBin.

I think the best way to prevent the automatic submission of the form is the following:

<form onsubmit="alert('Replace the alert with any validation code');return false;">
  <input name="name" class="name">
  <button type="submit" class="name__valid" value="save">save</button>
<form>

The event handler on the form itself handles when clicking the button AND when pressing the return key in the input field. Replace the alert function call with your Ajax validation but make sure you keep the return false;statement which prevents the automatic posting of the form.

</div>