Catering to Your Form-related Needs

Exclusive offer: get 50% off this eBook here
Sencha Touch Cookbook, Second Edition

Sencha Touch Cookbook, Second Edition — Save 50%

Over 100 hands-on recipes to help you understand the complete Sencha Touch framework and solve your day-to-day problems with this book and ebook

€23.99    €12.00
by Ajit Kumar | August 2013 | Cookbooks Open Source

In this article by Ajit Kumar, author of Sencha Touch Cookbook (2nd edition), we will go through all the form fields and understand how to make use of them and learn about their specific behaviors. Also, we will see how to create a form using one or more form fields, and handle form validation and submission.

In this article, we will cover the following topics:

  • Getting your form ready with form panels
  • Working with search
  • Applying custom validation in the e-mail field
  • Working with dates using the date picker
  • Making a field hidden
  • Working with the select field
  • Changing a value using slider
  • Spinning the number wheel using spinner
  • Toggling between your two choices
  • Checkbox and checkbox groups
  • Text and text area
  • Grouping fields with fieldset
  • Validating your form

(For more resources related to this topic, see here.)

Getting your form ready with form panels

This recipe shows how to create a basic form using Sencha Touch and implement some of the behaviors such as how to submit the form data and how to handle the errors during the submission.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps to create a form panel:

  1. Create a ch02 folder in the same folder where we had created the ch01 folder.
  2. Create and open a new file ch02_01.js and paste the following code into it:

    Ext.application({
    name: 'MyApp',
    requires: ['Ext.MessageBox'],
    launch: function() {
    var form;
    //form and related fields config
    var formBase = {
    //enable vertical scrolling in case the form exceeds the page
    height
    scrollable: 'vertical',
    standardSubmit: false,
    submitOnAction: true,
    url: 'http://localhost/test.php',
    items: [{//add a fieldset
    xtype: 'fieldset',
    title: 'Personal Info',
    instructions: 'Please enter the information above.',
    //apply the common settings to all the child items of the fieldset
    defaults: {
    required: true,//required field
    labelAlign: 'left',
    labelWidth: '40%'
    },
    items: [
    {//add a text feild
    xtype: 'textfield',
    name : 'name',
    label: 'Name',
    clearIcon: true,//shows the clear icon in the field when user
    types
    autoCapitalize : true
    },
    { //add a password field
    xtype: 'passwordfield',
    name : 'password',
    label: 'Password',
    clearIcon: false
    }, {
    xtype: 'passwordfield',
    name : 'reenter',
    label: 'Re-enter Password',
    clearIcon: true
    }, { //add an email field
    xtype: 'emailfield',
    name : 'email',
    label: 'Email',
    placeHolder: 'you@sencha.com',
    clearIcon: true
    }]
    }, {
    //items docked to the bottom of the form
    xtype: 'toolbar',
    docked: 'bottom',
    items: [
    {
    text: 'Reset',
    handler: function() {
    form.reset(); //reset the fields
    }
    },
    {
    text: 'Save',
    ui: 'confirm',
    handler: function() {
    //sumbit the form data to the url
    form.submit({
    success: function(form, result) {Ext.Msg.alert("INFO", "Form
    submitted!");},
    failure: function(form, result) {Ext.Msg.alert("INFO", "Form
    submission failed!");}
    });
    }
    }
    ]
    }
    ]
    };
    if (Ext.os.is.Phone) {
    formBase.fullscreen = true;
    } else { //if desktop
    Ext.apply(formBase, {
    modal: true,
    centered: true,
    hideOnMaskTap: false,
    height: 385,
    width: 480
    });
    }
    //create form panel
    form = Ext.create('Ext.form.Panel', formBase);
    Ext.Viewport.add(form);
    }
    });

  3. Include the following line of code in the index.html file:

    <script type="text/javascript" charset="utf-8"
    src = "ch02/ch02_01.js"></script >

  4. Deploy and access it from the browser. You will see a screen as shown in the following screenshot:

How it works...

The code creates a form panel with a fieldset inside it. The fieldset has four fields specified as part of its child items. The xtype config mentioned for each field tells the Sencha Touch component manager which class to use to instantiate them.

form = new Ext.form.FormPanel(formBase); creates the form and the other field components using the config defined as part of the formBase. The form.show(); code renders the form to the body, and that's how it will appear on the screen. url contains the URL where the form data will be posted upon submission. The form can be submitted in two ways:

  • By hitting Go on the virtual keyboard, or Enter on a field, which ends up generating the action event
  • By clicking on the Save button, which internally calls the submit() method on the form object

form.reset() resets the status of the form and its fields to the original state. So, if you had entered the values in the fields and clicked on the Reset button, all the fields would be cleared.

form.submit() posts the form data to the specified URL. The data is posted as an Ajax request using the POST method.

Use of useClearIcon on the field tells Sencha Touch whether it should show the clear icon in the field when the user starts entering values in it. On clicking this icon, the value in the field is cleared.

There's more...

In the preceding code, we saw how to construct a form panel, add fields to it, and handle events. Let us see what other non-trivial things we may have to do in the project and how we can achieve these using Sencha Touch.

Standard submit

This is an old and traditional way for posting form data to the server URL. If your application's need is to use the standard form submit rather than Ajax, you will have to set the standardSubmit property to true on the form panel. This is set to false by default. The following code snippet shows the usage of this property:

var formBase = {
scroll: 'vertical',
standardSubmit: true,
...

After this property is set to true on the form panel, form.submit() will load the complete page specified in the url property.

Submitting on field action

As we saw earlier, the form data automatically gets posted to the URL if the action event occurs (when the Go button or the Enter key is hit). In many applications, this default feature may not be desirable. To disable this feature, you will have to set submitOnAction to false on the form panel.

Post-submission handling

Say we posted our data to the URL. Now, either the call may fail or it may succeed. To handle these specific conditions and act accordingly, we will have to pass additional config options to the form's submit() method. The following code shows the enhanced version of the submit call:

form.submit({
success: function(form, result) {
Ext.Msg.alert("INFO", "Form submitted!");
},
failure: function(form, result) {
Ext.Msg.alert("INFO", "Form submission failed!");
}
});

In case the Ajax call (to post form data) fails, the failure() callback function is called and if it's successful, the success() callback function is called. This works only if the standardSubmit property is set to false.

Reading form data

To read the values entered into a form field, form panel provides the getValues() method, which returns an object with field names and their values. It is important that you set the name property on your form field otherwise that field value will not appear in the object returned by the getValues() method:

handler: function() {
console.log('INFO', form.getValues());
//sumbit the form data to the url
form.submit({
...
...

Loading data in the form fields

To set the form field values, the form panel provides record config and two methods, setValues() and setRecord(). The setValues() method expects a config object with name-value pairs for the fields. The following code shows how to use the setValues() method:

{
text: 'Set Data',
handler: function() {
form.setValues({
name:'Ajit Kumar',
email: 'ajit@wtc.com'
});
}
},
{
text: 'Reset',
...
...

The preceding code adds a new button named Set Data; by clicking on it, the form field data is populated as shown in the following screenshot. As we had passed values for the Name and Email fields they are set:

The other method, setRecord(),expects an instance of the Ext.data.Model class. The following code shows how we can create a model and use it to populate the form fields:

,
{
text: 'Load Data',
handler: function() {
Ext.define('MyApp.model.User', {
extend: 'Ext.data.Model',
config: {
fields: ['name', 'email']
}
});
var ajit = Ext.create('MyApp.model.User', {
name:'Ajit Kumar',
email:'ajit@wtc.com'
});
form.setRecord(ajit);
}
},
{
text: 'Reset',
...
...

We shall use setRecord() when our data is stored as a model, or we will construct it as a model to use the benefits of the model (for example, loading from a remote data source, data conversion, data validation, and so on) that are not available with the JSON presentation of the data.

While the methods help us to set the field values at runtime the, record config allows us to populate the form field values when the form panel is constructed. The following code snippet shows how we can pass a model at the time of instantiation of the form panel:

var ajit = Ext.create('MyApp.model.User', {
name:'Ajit Kumar',
email:'ajit@wtc.com'
});
var formBase = {
scroll: 'vertical',
standardSubmit: true,
record: ajit,
...

Working with search

We will go over each of the form fields and understand how to work with them. This recipe describes the steps required to create and use a search form field.

Getting ready

Make sure that you have set up your development.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_02.js.
  2. Open a new file ch02_02.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'searchfield',
    name: 'search',
    label: 'Search'
    }]
    };

  3. Include ch02_02.js in place of ch02_01.js in index.html.
  4. Deploy and access the application in the browser. You will see a form panel with a search field.

How it works...

A search field can be constructed using the Ext.field.Search class instance or using the xtype: 'searchfield' approach. A search form field implements the HTML5 <input> element with type="search". However, the implementation is very limited. For example, the search field in HTML5 allows us to associate a data list that it can use during the search, whereas this feature is not present in Sencha Touch. Similarly, the W3 search field defines a pattern attribute to allow us to specify a regular expression against which a user agent is meant to check the value, which is not supported yet in Sencha Touch. For more detail, you may refer to the W3 search field (http://www.w3.org/TR/html-markup/input.search.html) and the source code of the Ext.field.Search class.

There's more...

In the application, we often do not use a label for the search fields. Rather, we would like to show text, such as Search…, inside the field that will disappear when the focus is on the field. Let us see how we can achieve this.

Using a placeholder

Placeholders are supported by most of the form fields in Sencha Touch using the placeholder property. Placeholder text appears in the field as long as there is no value entered in it and the field does not have the focus. The following code snippet shows the typical usage of it:

{
xtype: 'searchfield',
name: 'search',
label: 'Search',
placeHolder: 'Search...'
}

Applying custom validation in the e-mail field

This recipe describes how to make use of the e-mail form field provided by Sencha Touch, and how to validate the value entered into it to find out whether the entered e-mail passes the validation rule or not.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_03.js.
  2. Open a new file ch02_03.js
  3. and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'emailfield',
    name : 'email',
    label: 'Email',
    placeHolder: 'you@sencha.com',
    clearIcon: true,
    listeners: {
    blur: function(thisTxt, eventObj) {
    var val = thisTxt.getValue();
    //validate using the pattern
    if (val.search("[a-c]+@[a-z]+[.][a-z]+") == -1)
    Ext.Msg.alert("Error", "Invalid e-mail address!!");
    else
    Ext.Msg.alert("Info", "Valid e-mail address!!");
    }
    }
    }]
    };

  4. Include ch02_03.js in place of ch02_02.js in index.html.
  5. Deploy and access the application in the browser.

How it works...

The Email field can be constructed using the Ext.field.Email class instance or using the xtype value as emailfield. The e-mail form field implements the HTML5 <input> element with type="email". However, similar to the search field, the implementation is very limited. For example, the e-mail field in HTML5 allows us to specify a regular expression pattern, which can be used to validate the value entered in the field.

Working with dates using the date picker

This recipe describes how to make use of the date picker form field provided by Sencha Touch, which allows the user to select a date.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_04.js.
  2. Open a new file ch02_04.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'datepickerfield',
    name: 'date',
    label: 'Date'
    }]
    };

  3. Include ch02_04.js in place of ch02_03.js in index.html.
  4. Deploy and access the application in the browser.

How it works...

The date picker field can be constructed using the Ext.field.DatePicker class instance or using the xtype: datepickerfield approach. The date picker form field implements the HTML <select> element. When the user tries to select an entry, it shows the date picker component with the slots for the month, day, and year for selection. After selection, when the user clicks on the Done button, the field is set with the selected value.

There's more...

Additionally, there are other things that can be done, such as setting a date to the current date or a particular date, or changing the order of appearance of month, day, and year. Let us see what it takes to accomplish this.

Setting the default date to the current date

To set the default value to the current date, the value property must be set to the current date. The following code shows how to do it:

var formBase = {
items: [{
xtype: 'datepickerfield',
name: 'date',
label: 'Date',
value: new Date(),

Setting the default date to a particular date

The default date is January 01, 1970. Let's suppose that you need to set the date to a different date but not the current date. To do so, you will have to set the value property using the year, month, and day properties, as follows:

var formBase = {
items: [{
xtype: 'datepickerfield',
name: 'date',
label: 'Date',
value: {year: 2011, month: 6, day: 11},

Changing the slot order

By default, the slot order is month, day, and year. You can change it by setting the slotOrder property of the picker property of date picker, as shown in the following code:

var formBase = {
items: [{
xtype: 'datepickerfield',
name: 'date',
label: 'Date',
picker: {slotOrder: ['day', 'month', 'year']}
}]
};

Setting the picker date range

By default, the date range shown by the picker is from 1970 till the current year. For our application need, if we have to alter the year range to a different range, then we can do so by setting the yearFrom and yearTo properties of the picker property of the date picker, as follows:

var formBase = {
items: [{
xtype: 'datepickerfield',
name: 'date',
label: 'Date',
picker: {yearFrom: 2000, yearTo: 2013}
}]
};

Making a field hidden

Often in an application, there would be a need to hide the fields that are not needed in a particular context but are required, and hence they need to be shown. In this recipe, we will see how to make a field hidden and show it conditionally.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Edit ch02_04.js and modify the code, as follows, by adding the hidden property:

    var formBase = {
    items: [{
    xtype: 'datepickerfield',
    id: 'datefield-id',
    name: 'date',
    hidden: true,
    label: 'Date'}]
    };

  2. Deploy and access the application in the browser.

How it works...

When a field is marked as hidden, Sencha Touch uses the DOM's hide() method on the element to hide that particular field.

There's more...

Let's see how we can programmatically show/hide a field.

Showing/hiding a field at runtime

Each component in Sencha Touch supports two methods, show() and hide(). The show() method shows the element and the hide() method hides the element. To call these methods, first we will have to find the reference to the component, which can be achieved by either using the object reference or by using the Ext.getCmp() method. Given a component ID, the getCmp() method returns us the component. The following code snippet demonstrates showing an element:

var cmp = Ext.getCmp('datefield-id');
cmp.show();

To hide an element, we will have to call cmp.hide().

Working with the select field

This recipe describes the use of the select form field, which allows the user to select a value from a list of choices, such as a combobox.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_05.js
  2. Open a new file ch02_05.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'selectfield',
    name: 'select',
    label: 'Select',
    placeHolder: 'Select...',
    options: [
    {text: 'First Option', value: 'first'},
    {text: 'Second Option', value: 'second'},
    {text: 'Third Option', value: 'third'}
    ]
    }]
    };

  3. Include ch02_05.js in place of ch02_04.js in index.html.
  4. Deploy and access the application in the browser.

How it works...

The preceding code creates a select form field with three options for selection. The select field can be constructed using the Ext.field.Select class instance or using the xtype: 'selectfield' approach. The select form field implements the HTML <select> element. By default, it uses the text property to show the text for selection.

There's more...

It may not always be possible or desirable to use text and value properties in the date to populate the selection list. In case we have a different property in place of text, then how do we make sure that the selection list is populated correctly without any further conversion? Let's see how we can do this.

Using a custom display value

We shall use displayField to specify the field that will be used as text, as shown in the following code:

{
xtype: 'selectfield',
name: 'select',
label: 'Second Select',
placeHolder: 'Select...',
displayField: 'desc',
options: [
{desc: 'First Option', value: 'first'},
{desc: 'Second Option', value: 'second'},
{desc: 'Third Option', value: 'third'}
]
}

Changing a value using slider

This recipe describes the use of the slider form field, which allows the user to change the value by mere sliding.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_06.js.
  2. Open a new file ch02_06.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'sliderfield',
    name : 'height',
    label: 'Height',
    minValue: 0,
    maxValue: 100,
    increment: 10
    }]
    };

  3. Include ch02_06.js in place of ch02_05.js in index.html.
  4. Deploy and access the application in the browser.

How it works...

The preceding code creates a slider field with 0 to 100 as the range of values, with 10 as the increment value; this means that, when a user clicks on the slider, the value will change by 10 on every click. The increment value must be a whole number.

Sencha Touch Cookbook, Second Edition Over 100 hands-on recipes to help you understand the complete Sencha Touch framework and solve your day-to-day problems with this book and ebook
Published: August 2013
eBook Price: €23.99
Book Price: €38.99
See more
Select your format and quantity:

Spinning the number wheel using spinner

This recipe describes the use of the spinner form field, which allows the user to change the value by clicking on the wheel.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_07.js.
  2. Open a new file ch02_07.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'spinnerfield',
    name : 'spinner',
    label: 'Spinner',
    minValue: 0,
    maxValue: 100,
    stepValue: 10,
    cycle: true
    }]
    };

  3. Include ch02_07.js in place of ch02_06.js in index.html.
  4. Deploy and access the application in the browser.

How it works...

Spinner is a wrapper around the HTML5 number field. The spinner field can be constructed by instantiating the Ext.field.Spinner class or using the xtype value as spinnerfield. minValue sets the initial value, which will be displayed in the field when the field is rendered. maxValue: 100 is the maximum value that will be displayed in this field. stepValue tells the framework that, on every click, the value will be incremented/decremented by 10 based on the direction in which the user is moving.

There's more...

In the spinner, it may be a more sensible thing to be able to recycle the value. The following section shows how to do this.

Recycling the values

By default, when the user reaches maxValue or minValue, he/she cannot move further. In this case, we may want to recycle the values. To do this, the Spinner class provides a cycle property; setting its value to true will ensure that the value is set to minValue when the user clicks after the field value has reached maxValue and vice versa. The following code snippet shows how to set this property:

items: [{
xtype: 'spinnerfield',
name : 'spinner',
label: 'Spinner',
minValue: 0,
maxValue: 100,
stepValue: 10,
cycle: true
}]

Toggling between your two choices

This is a specialized slider with only two values. In this recipe we will see how to make use of the toggle field.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_08.js.
  2. Open a new file ch02_08.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'togglefield',
    name : 'toggle',
    label: 'Toggle'
    }]
    };

  3. Include ch02_08.js in place of ch02_07.js in index.html.
  4. Deploy and access the application in the browser.

How it works...

This creates a slider field with minValue set to 0 and maxValue set to 1.

Checkbox and checkbox groups

Checkboxes permit the user to make multiple selections from a number of available options. It is a convenient way to learn about user choices. For example, in an application we may have a checkbox asking the user if he/she stayed in Hyderabad. And if we are capturing details about multiple cities where the user had stayed, then we would group multiple checkboxes under one name and use them as a checkbox group. In this recipe, we will see how we can create a checkbox and a checkbox group using Sencha Touch, and how to handle the values when you want to set them or when the form data is posted.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_09.js.
  2. Open a new file ch02_09.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [{
    xtype: 'checkboxfield',
    name: 'city',
    value: 'Hyderabad',
    label: 'Hyderabad',
    checked: true
    }, {
    xtype: 'checkboxfield',
    name: 'city',
    value: 'Mumbai',
    label: 'Mumbai'
    }]
    };

  3. Include ch02_09.js in place of ch02_08.js in index.html.
  4. Deploy and access the application in the browser. You shall see the checkboxes as shown in the following screenshot:

     

How it works...

The preceding code creates two checkboxes inside the form panel. checked:true<> checks the checkbox when it is rendered. When a form is submitted, the checkbox values are returned as an array. For example, given the previous code, when the user clicks on the Submit button, city would have two values, as follows:

city: ['Hyderabad', 'Mumbai']

Text and text area

A text field is one of the initial fields that allows the user to enter data in a form. Text area allows entering multiple lines of text. In this recipe we will make use of the text and text-area-related classes.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_10.js.
  2. Open a new file ch02_10.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [
    {
    xtype: 'textfield',
    name : 'firstName',
    label: 'First Name'
    },
    {
    xtype: 'textfield',
    name : 'lastName',
    label: 'Last Name'
    },
    {
    xtype: 'textareafield',
    name : 'detail',
    label: 'Detail'
    }]
    };

  3. Include ch02_10.js in place of ch02_09.js in index.html.
  4. Deploy and access the application in the browser.

How it works...

In the preceding code, we created two text fields and a text area. A text field can be constructed using the Ext.field.Text class instance or using the xtype value as textfield. Similarly, a text area can be constructed using the Ext.field.TextArea class instance or using xtype: textareafield. Internally, the text form field implements the HTML <input> element with type="text" whereas text area implements the HTML <textarea> element. There is no validation on these fields; hence, the user is allowed, by default, to enter any kind of value.

There's more...

By default, a text field or a text area allows entering any number of characters. However, in some specific scenario, we may have to limit this to a particular value in our application. Let us see how we can limit this.

Limiting the number of input characters

Both text fields and text areas support a property named maxLength that controls how many characters the user can enter. If this property is set to 20, the user can only enter 20 characters. The following code snippet shows how to do this:

{
xtype: 'textfield',
name : 'firstName',
maxLength: 20,
label: 'First Name'
},
{
xtype: 'textareafield',
name : 'detail',
maxLength: 80,
label: 'Detail'
}

Grouping fields with fieldset

Fieldset is used to logically group together elements in a form. This recipe shows what Sencha Touch class can be used to create and how it groups the items under a fieldset.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_11.js.
  2. Open a new file ch02_11.js and replace the definition of formBase with the following code:

    var formBase = {
    items: [
    {
    xtype: 'fieldset',
    title: 'About Me',
    items: [
    {
    xtype: 'textfield',
    name : 'firstName',
    label: 'First Name'
    },
    {
    xtype: 'textfield',
    name : 'lastName',
    label: 'Last Name'
    }
    ]
    }
    ]

  3. Include ch02_12.js in place of ch02_10.js in index.html.
  4. Deploy and access the application in the browser.

How it works...

Fieldsets can be constructed using the Ext.field.FieldSet class instance or the xtype value as fieldset. All the elements, which must be grouped under the fieldset, must be added to the fieldset as its child items. The FieldSet class implements the HTML <fieldset> tag and uses the legend element to show the title.

There's more...

Say, when you are grouping the elements under the fieldset, you also want a way to add some instructions for it to give more information to the user. The FieldSet class supports this and lets us see how to do it.

Adding instructions

The Ext.field.FieldSet class provides a property named instructions, which we can use to add additional instructions. The following code snippet shows how to set this property:

xtype: 'fieldset',
title: 'About Me',
instructions: 'Fill in your personal detail',

The specified instruction gets added to the bottom of the fieldset, as shown in the following screenshot:

Validating your form

So far, we have looked at how to create a form and make use of the different form fields offered by Sencha Touch. Different form fields provide different kinds of information a user can enter. Now, some of them may be valid and some may not be. It is a common practice to validate the form and the entered values at the time of posting. Now, based on your application architecture, you may choose to apply all kinds of validations in the frontend UI or you may choose to handle them in the backend server code, or a combination of the two. All of them are valid approaches. However, we would assume that we want to validate the form on the frontend to make sure that the values entered are valid.

Sencha Touch does not offer a mechanism to do form validation. As of now, it has no direct support for validating the inputs. If we intend to validate the form, the code has to be written to do so. There are various approaches to building the form validation capability, depending upon what level of abstraction and reusability we want to achieve. One can write specific code in each form to carry out the validation, or one can enhance the Ext.Component class, which is the base class for all the Sencha Touch components, or the Ext.field.Field classes to handle the validation in a more generic way. Alternatively, one can enhance the form panel as well to implement a nicely encapsulated form and field validation functionality. In this recipe, we will see how we can write the specific validation code to take care of our need. The author hopes that there will be a more streamlined validation in a future version of Sencha Touch.

Getting ready

Make sure that you have set up your development environment.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_12.js and modify the handler function with the following code:

    handler: function() {
    var isValid = true;
    var errors = new Array();
    var fieldValMap = form.getValues();
    var email = fieldValMap['email'];
    var name = fieldValMap['name'];
    //validate the name
    if (name.search(/[0-9]/) > -1) {
    isValid = false;
    errors.push({field : 'name',
    reason : 'Name must not contain numbers'});
    }
    //validate e-mail
    if (email.search("@") == -1) {
    isValid = false;
    errors.push({field : 'email',
    reason : 'E-mail address must contain @'});
    }
    //show error if the validation failed
    if (!isValid) {
    var errStr = "";
    Ext.each(errors, function(error, index){
    errStr += "[" + (index+1) + "] - " + error.reason + "\n";
    });
    Ext.Msg.alert("Error", errStr);
    } else {//form is valid
    form.submit();
    }
    }

  2. Include ch02_13.js in place of ch02_12.js in index.html.
  3. Deploy and access the application in the browser.

How it works...

The handler() function gets called when the user clicks on the Save button. The handler validates the name and the e-mail address field values. name.search(/[0-9]/) checks if the name entered contains any number and email.search("@") verifies if the e-mail address contains @ or not. In case of any error, we add an error object to the errors array with two properties, field and reason. The field property stores the field on which the validation had failed and the corresponding reason is stored in the reason property. After all the fields have been validated, we check the isValid flag to see if any of the field validation had failed; if so, we show up a message box with the list of errors, as shown in the following screenshot:

If there are no field validation errors, the form is submitted.

Summary

We created a form using Sencha Touch and the different form fields that can be used to work effectively with the forms, and also learned how to handle form validation and submission.

Resources for Article :


Further resources on this subject:


Sencha Touch Cookbook, Second Edition Over 100 hands-on recipes to help you understand the complete Sencha Touch framework and solve your day-to-day problems with this book and ebook
Published: August 2013
eBook Price: €23.99
Book Price: €38.99
See more
Select your format and quantity:

About the Author :


Ajit Kumar

Ajit Kumar started his IT career with Honeywell, Bangalore in the field of embedded systems and moved on to enterprise business applications (such as ERP) in his 13 years' career. From day one, he has been a staunch supporter and promoter of open source and believes strongly that open source is the way for a liberal, diversified, and democratic setup, such as India. He dreams, and continuously strives to ensure, that architecture, frameworks, and tools must facilitate software development at the speed of thought.

Ajit holds a Bachelor's degree in Computer Science and Engineering from the Bihar Institute of Technology, Sindri. He co-founded Walking Tree, which is based out of Hyderabad, India where he plays the role of CTO and works on fulfilling his vision.

Prior to writing this book, he worked on the following titles by Packt Publishing:

  • ADempiere 3.6 Cookbook
  • Sencha Touch Cookbook
  • Sencha MVC Architecture

Books From Packt


Sencha Architect App Development
Sencha Architect App Development

Sencha MVC Architecture
Sencha MVC Architecture

Sencha Touch Mobile JavaScript Framework
Sencha Touch Mobile JavaScript Framework

Ext JS 4 Web Application Development Cookbook
Ext JS 4 Web Application Development Cookbook

Sencha Touch 2 Mobile JavaScript Framework
Sencha Touch 2 Mobile JavaScript Framework

Sencha Touch Cookbook
Sencha Touch Cookbook

Creating Mobile Apps with Sencha Touch 2
Creating Mobile Apps with Sencha Touch 2

Ext JS 4 Plugin and Extension Development
Ext JS 4 Plugin and Extension Development


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software