Sencha Touch: Catering Form Related Needs

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

Sencha Touch Cookbook — Save 50%

Over 100 recipes for creating HTML5-based cross-platform apps for touch devices with this book and ebook

$26.99    $13.50
by Ajit Kumar | December 2011 | Cookbooks Java

This article covers every aspect of a form, including the different form fields offered by Sencha Touch, configuring each one of them for the user in a form, and configuring ways by which a typical form validation can be done. Fields such as Search, E-mail, DatePicker, Select, Slider, Checkbox, TextArea, FieldSet, and so on are covered in this article along with their detailed usage.

In this article by Ajit Kumar, author of Sencha Touch Cookbook, we will cover:

  • Getting your form ready with FormPanel
  • Working with search
  • Putting custom validation in the e-mail field
  • Working with dates using DatePicker
  • Making a field hidden
  • Working with the select field
  • Changing the value using Slider
  • Spinning the number wheel using Spinner
  • Toggling between your two choices
  • Checkbox and checkbox group
  • Text and TextArea
  • Grouping fields with FieldSet
  • Validating your form

(For more resources on Sencha Touch, see here.)

Most of the useful applications not only present the data, but also accept inputs from their users. When we think of having a way to accept inputs from the user, send them to the server for further processing, and allow the user to modify them, we think of forms and the form fields. If our application requires users to enter some information, then we go about using the HTML form fields, such as <input>, <select>, and so on, and wrap inside a <form> element. Sencha Touch uses these tags and provides convenient JavaScript classes to work with the form and its fields. It provides field classes such as Url, Toggle, Select, Text, and so on. Each of these classes provides properties to initialize the field, handle the events, and utility methods to manipulate the behavior and the values of the field. On the other side, the form takes care of the rendering of the fields and also handles the data submission.

Each field can be created by using the JSON notation (JavaScript Object Notationhttp://www.json.org) or by creating an instance of the class. For example, a text field can either be constructed by using the following JSON notation:

{ xtype: 'textfield', name: 'text', label: 'My Text' }

Alternatively, we can use the following class constructor:

var txtField = new Ext.form.Text({ name: 'text', label: 'My Text' });

The first approach relies on xtype, which is a type assigned to each of the Sencha Touch components. It is used as shorthand for the class. The basic difference between the two is that the xtype approach is more for the lazy initialization and rendering. The object is created only when it is required. In any application, we would use a combination of these two approaches.

In this article, we will go through all the form fields and understand how to make use of them and learn about their specific behaviors. In addition, we will see how to create a form using one or more form fields and handle the form validation and submission.

Getting your form ready with FormPanel

This recipe shows how to create a basic form using Sencha Touch and implement some of the behaviors such as submitting the form data, handling errors during the submission, and so on.

Getting ready

Make sure that you have set up your development environment

How to do it...

Carry out the following steps:

  1. Create a ch02 folder in the same folder where we had created the ch01 folder.
  2. Create and open a new file named ch02_01.js and paste the following code into it:
  3. Ext.setup({ onReady: function() { var form; //form and related fields config var formBase = { //enable vertical scrolling in case the form exceeds the page height scroll: 'vertical', 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 field xtype: 'textfield', name : 'name',

    label: 'Name', useClearIcon: true,//shows the clear icon in the field when user types autoCapitalize : false }, {//add a password field xtype: 'passwordfield', name : 'password', label: 'Password', useClearIcon: false }, { xtype: 'passwordfield', name : 'reenter', label: 'Re-enter Password', useClearIcon: true }, {//add an email field xtype: 'emailfield', name : 'email', label: 'Email', placeHolder: 'you@sencha.com', useClearIcon: true }] } ], listeners : { //listener if the form is submitted, successfully submit : function(form, result){ console.log('success', Ext.toArray(arguments)); }, //listener if the form submission fails exception : function(form, result){ console.log('failure', Ext.toArray(arguments)); } }, //items docked to the bottom of the form dockedItems: [ { xtype: 'toolbar', dock: 'bottom', items: [ { text: 'Reset', handler: function() { form.reset(); //reset the fields

    } }, { text: 'Save', ui: 'confirm', handler: function() { //submit the form data to the url form.submit(); } } ] } ] }; if (Ext.is.Phone) { formBase.fullscreen = true; } else { //if desktop Ext.apply(formBase, { autoRender: true, floating: true, modal: true, centered: true, hideOnMaskTap: false, height: 385, width: 480 }); } //create form panel form = new Ext.form.FormPanel(formBase); form.show(); //render the form to the body } });

     

  4. Include the following line in index.html:
  5. <script type="text/javascript" charset="utf-8" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="ch02/ch02_01.js"></script>

  6. Deploy and access it from the browser. You will see the following screen:

How it works...

The code creates a form panel, with a field set inside it. The field set has four fields specified as part of its child items. xtype mentioned for each field instructs 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.

form.show() renders the form to the body and that is 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 the following two ways:

  1. By hitting Go, on the virtual keyboard or Enter on a field that ends up generating the action event.
  2. 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. Therefore, 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 instructs Sencha Touch whether it should show the clear icon in the field when the user starts entering a value in it. On clicking on 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. We will 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 the old and traditional way for form data posting to the server url. If your application need is to use the standard form submit, rather than Ajax, then you will have to set standardSubmit 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 FormPanel, form.submit() will load the complete page specified in url.

Do not submit on field action

As we saw earlier, the form data is automatically posted to the url if the action event (when the Go or Enter key is hit) occurs. In many applications, this default feature may not be desirable. In order 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. In order 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!"); } });

If the Ajax call (to post form data) fails, then the failure callback function is called, and in the case of success, the success callback function is called. This works only if the standardSubmit is set to false.

Working with search

In this and the subsequent recipes of the article, 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 environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_02.js.
  2. Open a new file named ch02_02.js and replace the definition of formBase with the following code:
  3. var formBase = { items: [{ xtype: 'searchfield', name: 'search', label: 'Search' }] };

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

How it works...

The search field can be constructed by using the Ext.form.Search class instance or by using the xtype—searchfield. The search form field implements HTML5 <input> with type="search". However, the implementation is very limited. For example, the HTML5 search field allows us to associate a data list to it which it can use during the search, whereas this feature is not present in Sencha Touch. Similarly, the W3 search field spec 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.form.Search class.

There's more...

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

Using a placeholder

Placeholders are supported by most of the form fields in Sencha Touch by using the property placeHolder. The 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...' }

Putting 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.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_03.js.
  2. Open a new file named ch02_03.js and replace the definition of formBase with the following code:
  3. var formBase = { items: [{ xtype: 'emailfield', name : 'email', label: 'Email', placeHolder: 'you@sencha.com', useClearIcon: 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 e-mail field can be constructed by using the Ext.form.Email class instance or by using the xtype: emailfield. The e-mail form field implements HTML5 <input> with type="email". However, as with the search field, the implementation is very limited. For example, the HTML5 e-mail field allows us to specify a regular expression pattern which can be used to validate the value entered in the field.

Working with dates using DatePicker

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.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_04.js.
  2. Open a new file named ch02_04.js and replace the definition of formBase with the following code:
  3. var formBase = { items: [{ xtype: 'datepickerfield', name: 'date', label: 'Date' }] };

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

How it works...

The date picker field can be constructed by using the Ext.form.DatePicker class instance or by using xtype: datepickerfield. The date picker form field implements HTML <select>. When the user tries to select an entry, it shows the date picker with the month, day, and year slots 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 the date to the current date, or any particular date, or changing the order of appearance of a month, day, and year. Let's see what it takes to accomplish this.

Setting the default date to the current date

In order 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 01/01/1970. Let's assume 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 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 1970 until the current year. For our application need, if we have to alter the year range, we can do so by setting the yearFrom nd 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: 2010} }] };

Making a field hidden

Often in an application, there would be a need to hide fields which are not needed in a particular context but are required and hence need to be shown in another. 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.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

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:
  2. var formBase = { items: [{ xtype: 'datepickerfield', id: 'datefield-id', name: 'date', hidden: true, label: 'Date'}] };

  3. 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 hide hides the element. In order to call these methods, we will have to first 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 how to show an element:

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

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

Sencha Touch Cookbook Over 100 recipes for creating HTML5-based cross-platform apps for touch devices with this book and ebook
Published: December 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

(For more resources on Sencha Touch, see here.)

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 combo box.

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_05.js.
  2. Open a new file named ch02_05.js and replace the definition of formBase with the following code:
  3. 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'}
    ]
    }]
    };

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

How it works...

 

The preceding code creates a select form field with the three options for selection. The select field can be constructed by using the Ext.form.Select class instance or by using the xtype—selectfield. The select form field implements HTML <select>. 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. If 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 the custom display value

We, 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',
hiddenName: 'second-select'
,options: [
{desc: 'First Option', value: 'first'},
{desc: 'Second Option', value: 'second'},
{desc: 'Third Option', value: 'third'}
]
}

Changing the value using Slider

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

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_06.js.
  2. Open a new file named ch02_06.js and replace the definition of formBase with the following code:
  3. var formBase = {
    items: [{
    xtype: 'sliderfield',
    name : 'height',
    label: 'Height',
    minValue: 0,
    maxValue: 100,
    increment: 10
    }]
    };

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

How it works...

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

Spinning the number wheel using Spinner

This recipe describes the use of a 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.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_07.js.
  2. Open a new file named ch02_07.js and replace the definition of formBase with the following code:
  3. var formBase = {
    items: [{
    xtype: 'spinnerfield',
    name : 'spinner',
    label: 'Spinner',
    minValue: 0,
    maxValue: 100,
    incrementValue: 10,
    cycle: true
    }]
    };

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

How it works...

Spinner is a wrapper around the HTML5 number field. A spinner field can be constructed by using the Ext.form.Spinner class instance or by using the xtype—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. incrementValue instructs 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 recycle the value. The following section shows how to do this.

Recycling the values

By default, when the user reaches the maxValue or the minValue, he/she cannot move further. In this case, we may want to recycle the values. In order to do this, the spinner class provides a cycle property and setting its value to true will ensure that the value is set to minValue when the user clicks after the field value had reached the 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,
incrementValue: 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.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_08.js.
  2. Open a new file named ch02_08.js and replace the definition of formBase with the following code:
  3. var formBase = {
    items: [{
    xtype: 'togglefield',
    name : 'toggle',
    label: 'Toggle'
    }]
    };

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

How it works...

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

Checkbox and Checkbox group

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. Moreover, if we are capturing the detail 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.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_09.js.
  2. Open a new file named ch02_09.js and replace the definition of formBase with the following code:
  3. var formBase = {
    items: [{
    xtype: 'checkboxfield',
    name: 'city',
    value: 'Hyderabad',

    label: 'Hyderabad',
    checked: true
    }, {
    xtype: 'checkboxfield',
    name: 'city',
    value: 'Mumbai',
    label: 'Mumbai'
    }]
    };

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

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 preceding code, when the user clicks on Submit, city would have two values, as follows:

     city: ['Hyderabad', 'Mumbai']

Text and TextArea

Text fields are one of the initial fields which allow 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.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_10.js.
  2. Open a new file named ch02_10.js and replace the definition of formBase with the following code:
  3. var formBase = {
    items: [
    {
    xtype: 'textfield',
    name : 'firstName',
    label: 'First Name'
    },
    {
    xtype: 'textfield',

    name : 'lastName',
    label: 'Last Name'
    },
    {
    xtype: 'textareafield',
    name : 'detail',
    label: 'Detail'
    }
    ]
    };

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

How it works...

In the preceding code, we created two text fields and a text area. Text field can be constructed by using the Ext.form.Text class instance or by using the xtype—textfield. Similarly, a text area can be constructed by using the Ext.form.TextArea class instance or by using xtype—extareafield. 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 scenarios, we may have to limit this to a particular value in our application. Let's see how we can limit this.

Limiting the number of input characters

Both text field and text area support a property named maxLength which controls the number of characters the user can enter. If this property is set to 20, then 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, an example of which we saw in he first recipe of this article. This recipe shows how the Sencha Touch class can be used to create and group items under FieldSet.

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_12.js.
  2. Open a new file named ch02_12.js and replace the definition of formBase with the following code:
  3. var formBase = {
    items: [
    {
    xtype: 'fieldset',
    title: 'About Me',
    items: [

    {
    xtype: 'textfield',
    name : 'firstName',
    label: 'First Name'
    },
    {
    xtype: 'textfield',
    name : 'lastName',
    label: 'Last Name'
    }
    ]
    }
    ]
    };

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

How it works...

FieldSets can be constructed by using the Ext.form.FieldSet class instance or by using the xtype—fieldset. All elements which must be grouped under the field set must be added to the field set as child items. The FieldSet class implements the HTML <fieldset> element and uses legend to show the title.

There's more...

Suppose, when you are grouping the elements under the field set, you also want a way to add some instructions for it, to give more information to the user. The FieldSet class supports this and we will now see how to do it.

Adding instructions

The Ext.form.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 is added at the bottom of the field set as shown in the following screenshot:

Validating your form

So far, we have looked at how to create a form and make use of 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. 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 are valid approaches. However, for this article, we would assume that we want to validate the form on the frontend to make sure that the values entered are valid. encha 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, then 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 re-usability we want to achieve. We can write a specific code in each form to carry out the validation or we can enhance Ext. omponent, which is the base class for all the Sencha Touch components, or the Ext. orm.Field classes to handle the validation in a more generic way. Alternatively, we can enhance FormPanel, 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

Getting ready

Make sure that you have set up your development environment.

Make sure that you have followed the Getting your form ready with FormPanel recipe in this article.

How to do it...

Carry out the following steps:

  1. Copy ch02_01.js to ch02_13.js and modify the handler function with the following code:
  2. 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();
    }
    }

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

How it works...

The handler function is 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 numbers and email.search("@") verifies if the e-mail address contains @ or not. In case of an error, we are adding 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 are checking the isValid flag to see if any of the field validation had failed and, 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, then the form is submitted.

Summary

In this article, we covered every aspect of a form, including the different form fields offered by Sencha Touch, configuring each one of them for the user in a form, and configuring ways by which a typical form validation can be done. Fields such as Search, E-mail, DatePicker, Select, Slider, Checkbox, TextArea, FieldSet, and so on were also covered



Sencha Touch Cookbook Over 100 recipes for creating HTML5-based cross-platform apps for touch devices with this book and ebook
Published: December 2011
eBook Price: $26.99
Book Price: $44.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


Android Application Testing Guide
Android Application Testing Guide

Android User Interface Development: Beginner's Guide
Android User Interface Development: Beginner's Guide

Android 3.0 Animations: Beginner’s Guide
Android 3.0 Animations: Beginner’s Guide

Flash Development for Android Cookbook
Flash Development for Android Cookbook

Android 3.0 Application Development Cookbook
Android 3.0 Application Development Cookbook

OS Development using MonoTouch Cookbook book
OS Development using MonoTouch Cookbook book

Phone Applications Tune-Up
Phone Applications Tune-Up

iPhone JavaScript Cookbook
iPhone JavaScript Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
h
Z
Y
v
X
L
Enter the code without spaces and pay attention to upper/lower case.
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