Titanium Studio – More Javascript form validators

For the record, I don’t claim any expertise with regular expressions (regex). I found an excellent real-time regex creator from Grant Skinner here. Thanks, Grant.

I took his pre-formed regular expression for validating email and incorporated it into my own javascript code for my current project. Hope it’s able to save others development time.

I start with a typical registration page with first and last name, email, and password and password verify fields. I wrap the whole thing in a validateInput() function, then call the function in an event listener. Notice that I set local variables with an underscore (_) prefix so that I don’t confuse them with the actual fields.

function validateInput() {
    var _firstName = firstNameField.value;
    var _lastName = lastNameField.value;
    var _email = emailField.value;
    var _password = passwordField.value;
    var _passwordVerify = passwordVerifyField.value;

    var noBlanks = false;
    var noNumbers = true;
    var isValidEmail = false;
    var passwordMatch = false;

    //variable must be initialized to an empty string.
    var alertMessage = '';

    var w = Ti.UI.createWindow({
        url : '',
        firstName : _firstName,
        lastName : _lastName,
        tabBarHidden : false
    });

    if(_firstName !== "" && _lastName !== "") {
        noBlanks = true;
    } else {
        alertMessage += 'Please provide a first and last name.\n';
    }

    //VALIDATE EMAIL ADDRESS
    var validateEmail = /([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/g;

    if(validateEmail.test(_email) && _email !== '') {
        isValidEmail = true;
    } else {
        if(_email === '') {
            alertMessage += 'Please enter a valid email address.\n';
        } else {
            alertMessage += _email + ' is invalid. Please re-enter.\n';
        }
    }

    //VALIDATE PASSWORD MATCH
    if(_password === _passwordVerify && _password !== '') {
        passwordMatch = true;
    } else {
        if(_password === '') {
            alertMessage += 'Passwords cannot be blank.';
        } else {
            alertMessage += ' Password mismatch.\nPlease re-enter password.';
        }
    }

    //TEST FIELDS FOR NUMBER CHARACTERS
    var hasNumbers = /[0-9]+(?:\.[0-9]*)?/;
    var testFields = [_firstName, _lastName];

    for(var i = 0, j = testFields.length; i < j; i++) {
        if(hasNumbers.test(testFields[i])) {
            alertMessage += 'First and last name fields cannot contain numbers.';
            noNumbers = false;
            break;
        }
    }
    // VALIDATE INPUT
    if(noNumbers === true && noBlanks === true && isValidEmail === true && passwordMatch === true) {
        w.open();
    } else {
        var invalidInputAlert = Titanium.UI.createAlertDialog({
            title : 'Attention',
            message : alertMessage
        });
        invalidInputAlert.show();
    }
}

I’ve bolded the two regex variables so they’re easier to locate.

To summarize, I have my field values plugged into local variables, and I have some boolean validation variables. I then test the input for each simple validation rule — no blanks for first and last name (I don’t test for length), regex for valid email address construction, check that password fields aren’t blank and they match, and finally first/last name does not contain numbers. I assign the results to boolean variables, test the boolean values for false, which equals failure, then pass a concatenated error message to an alert dialog.

If any of this is incorrect or confusing, or can be tightened up, please feel free to post a comment.

Happy coding.

Advertisement

Leave a Comment

Filed under Javascript, Titanium Studio

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s