Łukasz Naróg
Łukasz Naróg

Reputation: 59

async js validation form

Good morning ! Currently I am trying to create some kind of simple validation using javascript, but I have a problem with using async functionalities.

Below you can see UI method which iterates through validityChecks collections

    checkValidity: function(input){
        for(let i = 0; i<this.validityChecks.length; i++){

            var isInvalid = this.validityChecks[i].isInvalid(input);//promise is returned
            if(isInvalid){
                this.addInvalidity(this.validityChecks[i].invalidityMessage);
            }

            var requirementElement = this.validityChecks[i].element;
            if(requirementElement){
                if(isInvalid){
                    requirementElement.classList.add('invalid');
                    requirementElement.classList.remove('valid');
                }else{
                    requirementElement.classList.remove('invalid');
                    requirementElement.classList.add('valid');
                }
            }
        }
    }

Below is specific collection object which is not working as it was intended

var usernameValidityChecks = [
    {
        isInvalid: function(input){
            var unwantedSigns = input.value.match(/[^a-zA-Z0-9]/g);
            return unwantedSigns ? true:false;
        },
        invalidityMessage:'Only letters and numbers are allowed',
        element: document.querySelector('.username-registration li:nth-child(2)')
    },
    {
        isInvalid: async function (input){
            return await checkUsername(input.value);
        },
        invalidityMessage: 'This value needs to be unique',
        element: document.querySelector('.username-registration li:nth-child(3)')
    }

]
function checkUsername (username) {
    return new Promise ((resolve, reject) =>{
        $.ajax({
            url: "check.php",
            type: "POST",
            data: { user_name: username },
            success: (data, statusText, jqXHR) => {
                resolve(data);
            },
            error: (jqXHR, textStatus, errorThrown) => {
                reject(errorThrown);
            }
        });
    });
}

The problem is that to var isInvalid in checkValidity method is returned promise. Can anyone advice how to returned there value instead of promise ? Or how to handle promise there ? Thank you in advance!
EDIT :
Forgive me, but it is my first time with Stack and probably my question is a little bit inaccurate. Some of objects in collections are also synchronous, I changed usernameValidityChecks. How to handle this kind of situation ?
Where I have async and sync method at the same time ?

Upvotes: 3

Views: 510

Answers (2)

Harsh Verma
Harsh Verma

Reputation: 46

Instead of below line

var isInvalid = this.validityChecks[i].isInvalid(input);

you can use below code to make code much cleaner and store the desired value on the variable however above suggested solutions are also correct

var isInvalid = await this.validityChecks[i].isInvalid(input).catch((err) => { console.log(err) });

After this line you will get the desired value on isInvalid variable

And also add async keyword in all other isInvalid function definition

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44125

Use .then to access the result of a promise:

var isInvalid = this.validityChecks[i].isInvalid(input).then(res => res);

Upvotes: 0

Related Questions