How to Add JavaScript Form Validation to a Mobile App

Validating user input is one of the most important requirements in a mobile app. The most common approach of form validation requires that you check the form fields before the form is submitted; this is to make sure that the required information is supplied. Today we will show you how you can validate the input fields in your app before submitting the information to the Appery.io Database.

In this example the app will have following simple design:

Form App design

Form app design

Three Input components with the following placeholders: Name, AddressEmail, and “Submit” Button.

These Inputs have Types: text, text and email respectively. We will also need to add additional properties for all of our inputs – select More properties, and add attribute and value type to required. Don’t forget to click the ‘Add’ and ‘Save options’. Your final result should look like the screen shot below.

Input properties

Input properties

JavaScript validation logic

All logic will be placed on a Run Action JavaScript which with one click will run.

// Initial 'valid' variable state and a message string variable. 
var valid = true,
    message = 'The following fields are required: \n';
    
    // Here we are looking for a "required" in DOM elements by using jQuery
    // and filter only the ones which are visible (filled)
    // and saving the scope state
    $('*[required="required"]').filter(':visible:enabled').each(function() {
        var $this = $(this);
        
        // the condition which will check if the required elements doesn't have any values
        // we read placeholders values and switching 'valid' variable value to 'false'
        // and concatenating names of placeholders for a message string which will be shown to user 
        if(!$this.val()) {
            var inputName = $this.attr('placeholder');
            valid = false;
            message += '- ' + inputName + '\n';
        }
    });
    
    // Here we check our initial 'valid' variable is true or not.
    if(!valid) {
        // And here we informing user which fields are not filled out.
        alert(message);
    } else { 
    // Here for example we can invoke service with name 'submit_data' which will submit all input values to our Database.
    submit_data.execute({});
}
};

We are now ready to test our app, after clicking the “Submit” button you will see a warning message, which tells the user which fields are not filled out:

App Result

Validation result

This example shows how you can use custom JavaScript logic with Appery.io and check if the all fields in the form have been entered and ready to be submitted into the Database.