Titanium Studio – modal window toolbar

This code was nicked directly from CSSGallery. My thanks to them. I lost track of this code once. I’m not letting that happen again.

——————-

// create modal window
var modalWindow = Ti.UI.createWindow({
modal : true,
navBarHidden : true,
title : ‘Number of Players?’
});

//create toolbar
var cancel = Titanium.UI.createButton({
title : ‘Cancel’,
style : Titanium.UI.iPhone.SystemButtonStyle.BORDERED
});

var done = Titanium.UI.createButton({
title : ‘Done’,
style : Titanium.UI.iPhone.SystemButtonStyle.DONE
});

var spacer = Titanium.UI.createButton({
systemButton : Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
});

var toolbar = Titanium.UI.createToolbar({
top : 0,
items : [cancel, spacer, done]
});

var counterField = Ti.UI.createTextField({
hintText : ‘Enter number of players (max4)’,
value : ”
});

modalWindow.add(toolbar);

Leave a comment

Filed under Titanium Studio

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.

1 Comment

Filed under Javascript, Titanium Studio

Begin a validation library – form validation

In part to help other developers, and in part so that I don’t forget, I’ll post the beginnings of a Titanium Studio form validation library. This is what I created today.

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

var testFields = [ADD FIELD NAMES LIST HERE];

var hasNumberAlert = Titanium.UI.createAlertDialog({
title : ‘Attention:’,
message : ‘Fields cannot contain numbers.’
});

for(var i = 0, j = testFields.length; i < j; i++) {
if(hasNumbers.test(testFields[i])) {
hasNumberAlert.show();
noNumbers = false;
break;
}
}
// VALIDATE INPUT
if(noNumbers === true) {
Titanium.UI.window.open();
}
});

As always, feel free to post comments on ways to improve this code or your questions here.

Happy coding.

Leave a comment

Filed under iOS SDK, Javascript, Software, Titanium Studio

State which state you’re in… Titanium iOS US state picker

Last time, I discussed creating an iOS date picker; a code piece that is used quite extensively in app development. I hope it saved you some time.

Today, playing off the “picker” theme, I’ll post the US State picker code. It’s comparable to the date-picker. The difference is that you need to populate the values yourself. So, without further adieu…

First, create your picker_view, picker, and animation variables:

// CREATE STATE PICKER VIEW
var state_picker_view = Titanium.UI.createView({
height:250,
bottom:-250
});
win.add(state_picker_view);

var statePicker = Titanium.UI.createPicker({
selectionIndicator:true
});
state_picker_view.add(statePicker);

//ANIMATION VARIABLES
var slide_in = Titanium.UI.createAnimation({
bottom:50
});

var slide_out = Titanium.UI.createAnimation({
bottom:-250
});

Next, the really tedious part: creating the array. Here’s the code so you don’t have to do it yourself.

//INITIALIZE THE ARRAY

var data = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Virgin Islands', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

I’ll assign the values to the array using a simple for loop:

//ASSIGN VALUES TO PICKER ROWS
for(var i = 0, j = data.length; i < j; i++) {
statePicker.add(Titanium.UI.createPickerRow({
title:data[i]
}));
}

Next, create the field that receives the selected value and add it to the view:

// CREATE STATE TEXT FIELD
var txtState = Titanium.UI.createTextField({
//hintText:’Enter City’,
value:statePicker.value,
height:30,
top:200,
left:125,
width:145,
color:appFontColor,
autocorrect:false,
autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
returnKeyType:Titanium.UI.RETURNKEY_NEXT,
font:{fontFamily:appFont},
editable:false
});
viewMain.add(txtState);

Although I set the editable property to false, I don’t think it’s working properly. If you have the time, please verify and post your findings here. Also, remember to modify top, left, height, and width properties accordingly.

Next, create the toolbar like we did for the date-picker:

var btnCancelState = Titanium.UI.createButton({
title:’Cancel’,
style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
});

var btnDoneState = Titanium.UI.createButton({
title:’Done’,
style:Titanium.UI.iPhone.SystemButtonStyle.DONE
});

var toolbarState = Titanium.UI.createToolbar({
top:0,
items:[btnCancelState, spacer, btnDoneState]
});

And finally, add your event listeners:

//STATE FIELD EVENT LISTENERS
btnChooseState.addEventListener(‘click’, function() {
btnChooseDate.removeEventListener(‘click’,function(){});
state_picker_view.add(toolbarState);
state_picker_view.animate(slide_in);
});

//UPDATE VALUE IF CHANGED
statePicker.addEventListener(‘change’, function() {
txtState.value = statePicker.getSelectedRow(0).title;
});

btnCancelState.addEventListener(‘click’, function() {
state_picker_view.animate(slide_out);
});

btnDoneState.addEventListener(‘click’, function() {
txtState.value = statePicker.getSelectedRow(0).title;
state_picker_view.animate(slide_out);
});

There you have it. As always, I hope my work can save you precious development time.

Happy coding.

Leave a comment

Filed under Development, iOS SDK, Javascript, Software, Titanium Studio

Tutorials in the pipeline

Don’t have time to post them yet. But look for these handy Titanium Studio tips:
How to take/upload a photo
Copy this handy US State picklist (UIPicker)

Leave a comment

Filed under Debriefing

Titanium Studio – iOS date picker

I don’t know. Was it was my unfamiliarity with Titanium Studio, a javascript-based cross-platform mobile app development environment,

Finished product

or the fact that I haven’t developed in javascript in over 2 years? Whatever it was, it took me more hours than I’d care to admit to figure out how to make what I thought would be a simple date picker that populates a text field with the selection. Here’s a shot of the finished product.

As you can see, nothing special. It’s a very familiar interface for iPhone users. Imagine my surprise when I found almost no documentation or tutorials to walk me through this process. Well, let me rectify that oversight.

Let’s start with the basic window constructor. Since this editor doesn’t appear to have a tag for inserting code, I’ll use a block-quote.

var win = Titanium.UI.currentWindow;

var picker_view = Titanium.UI.createView({

height:251,

bottom:-251

});

win.add(picker_view);

Notice the height and bottom properties. Setting the bottom value equal to the inverse of the height allows us to have the picker slide in from the bottom.

Next comes the selector buttons and toolbar.

//CREATE SELECTOR BUTTONS

var cancel =  Titanium.UI.createButton({

title:’Cancel’,

style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED});

var done =  Titanium.UI.createButton({

title:’Done’,

style:Titanium.UI.iPhone.SystemButtonStyle.DONE});

var spacer =  Titanium.UI.createButton({

systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE});

var toolbar =  Titanium.UI.createToolbar({

top:0,

items:[cancel,spacer,done]});

After constructing the toolbar, we set the date picker values like this:

//Set initial value to today’s date.

var dateValue = new Date();

var minDate = new Date();

minDate.setFullYear(1900);

minDate.setMonth(0);

minDate.setDate(1);

//maxDate cannot be greater than today’s date.

var maxDate = dateValue;

var picker = Ti.UI.createPicker({

type:Ti.UI.PICKER_TYPE_DATE,

minDate:minDate,

maxDate:maxDate,

value:dateValue,

selectionIndicator:true // turn on the selection indicator (off by default)});

picker_view.add(picker);

picker_view.add(toolbar);

Since in this example, the date picker is used to assign a birthdate, I set maxDate equal to dateValue which grabs today’s date from the Date() object. I also set the minDate to 1900, but this is optional. And then I added the picker and toolbar to the view.

I added the animation variables

var slide_in =  Titanium.UI.createAnimation({bottom:0});

var slide_out =  Titanium.UI.createAnimation({bottom:-251});

Notice I set the slide_out bottom property to -251. This gives the appearance that the picker flys in from the bottom. Finally, I add the event listeners.

//CANCEL BUTTON

cancel.addEventListener(‘click’, function() {

picker_view.animate(slide_out);

});

//UPDATE VALUE IF CHANGED

datePicker.addEventListener(‘change’, function() {

textField.value = datePicker.value;});

//SET TEXTFIELD VALUE AND CLOSE PICKER

done.addEventListener(‘click’, function() {

textField.value = datePicker.value;

picker_view.animate(slide_out);

});

If the user presses Cancel, the picker flies out. If the picker value changes, update it. Once the user selects a date and presses Done, the value gets passed back to the assigned text field. One key point that took me a long time to figure out. A date picker’s return value is simply picker.value. This is different than a custom picker’s return value which is derived from picker.getSelectRow(0).propertyName (usually the title property).

I hope this helps someone else save a whole lot of time. If you find an error or typo, just post the correction here.

Happy Coding.

1 Comment

Filed under Development

Re-incarnation

Here we go again. Over the years, I’ve tried to sustain an interest in blogging. For the most part, my efforts sporadic at best. So, it’s time again to give it a whirl. I won’t promise any extended effort, but if I run across something I think is newsworthy I’ll post it here.

Leave a comment

Filed under Debriefing