I want to validate some values with javascript and the though process is like this:
- I fire an event when user submits form
- Javascript gets the values and validates them. If they are correct continue with number three, if not, return abortively.
- Make ajax request
Here is my submit function:
submitLoginForm: function (event) {
event.preventDefault();
// get the values
var object = this._getFormValues();
// make ajax request
this.querySelector('#postLoginForm').body = object;
this.querySelector('#postLoginForm').generateRequest();
},
This is the function that grabs the values
_getFormValues: function () {
var email = this.querySelector('#email').value;
var password = this.querySelector('#password').value;
var remember = this.querySelector('#remember').value;
this._validate(email, password);
return { 'email': email, 'password': password, 'remember': remember };
}
And this is the function that validates the fields or returns
_validate: function (email, password) {
if (email === '' || password === '') {
var elements = this.querySelectorAll('.form-group');
for (var i = 0; i < elements.length; i++) {
elements[i].className += ' has-error';
};
this.hasError = true;
this.errorMessage = 'Email and Password are required fields.'
return;
}
},
Till now I used early return like this:
if ('email' === '') {
return;
}
makeAjaxRequest();
But since I have nested functions, I wonder how to abort the process completely, if the fields don't validate.
Something like an exit() function would be nice.
Aucun commentaire:
Enregistrer un commentaire