mercredi 3 février 2016

Javascript: Stop Code Execution with Conditional Statement in Nested Functions

I want to validate some values with javascript and the though process is like this:

  1. I fire an event when user submits form
  2. Javascript gets the values and validates them. If they are correct continue with number three, if not, return abortively.
  3. 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