Learning Ext JS 3

Simple validations in the forms Más videos

Descripción del tema

The validations are very important when we're saving the information the user entered, we should always validate the information we receive. In today's tutorial we will see how to use the validations ExtJS provides. It is very important to remember that we must validate the information the user enters in our application, both sides are equally important: the client side and server side. Using JavaScript, we can provide a better user experience when entering information in our application, but we must not forget that the server is responsible to validate everything it receives therefore we also have to do validate the information on the server and show the errors when they occurred. This is a complicated task, but with Ext JS we can do this process faster by using the validations the Framework provides us. In this tutorial we will validate common information but later I will show you how to do complex validations.

Resources

Let's download the resources for this tutorial, I have created a form with common fields such as "name, date, e-mail, Website, comment", also there's a PHP file which returns randomly some validation errors that we will show in the forms.

Demo

For everyone's benefit I've created a demo of what we will see at the end of the tutorial, so go ahead a try it.
Validations in Ext JS

Example of the tutorial finished

Required fields

If you run the application right now you will see that an empty form is displayed, if we click on the "Save" button a request to the server is made through Ajax, then we get a message of "success" or "error". It is very common to have required fields in an application, we should make sure that these fields are entered by the user and are being sent to the server (through Ajax). To define a field as required we only need to use the property "allowBlank: false" in the fields we want to make mandatory, we will modify the form as follows.
this.form = new Ext.form.FormPanel({
	url: 'simplevalidations.php',
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Name',name:'name',allowBlank:false}, //required field
		{xtype:'datefield',fieldLabel:'Start',name:'start',allowBlank:false}, //required field
		{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006],readOnly:true},
		{fieldLabel:'Email',name:'email'},
		{fieldLabel:'Web site',name:'website'},
		{xtype:'textarea',fieldLabel:'Comment',name:'comment',allowBlank:false},//required field
		{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}
	]
});
In the previous code I've added the property "allowBlank: false" to the required fields, if you refresh the tutorial in your browser and click on the button "Save" you will get an error message and the required fields will be shown in red.
Validations in Ext JS

Required field in the form

Maximum of character in a TexField

Normally we define in the database the number of characters we want in a field, so it is recommended to make sure the user can only enter something less to that number, otherwise we will have problems when saving the information. To do this we need only set the property "maxLength" with the maximum number we need.
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		{fieldLabel:'Name',name:'name',allowBlank:false,maxLength:20},
		//… code removed for simplicity
	]
});
Now when we enter more than 20 characters in the field "name" an error appears telling us that something is wrong.
Validations in Ext JS

Restrict number of characters in a field

Common validations

Ext JS has a component that contains some common validations and we can add the validations we need, in this tutorial we will use the default ones. The component responsible of saving these validations is the "Ext.form.VTypes" and has four default validations:

Only alpha characters

The alpha characters are all letters and the underscore, it does not include numbers or other symbols. Let's assign a "VType" to the field "name" to accept only these characters.
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		{fieldLabel:'Name',name:'name',allowBlank:false,maxLength:20,vtype:'alpha'},
		//… code removed for simplicity
	]
});
With the property "VType" we can configure the validation we need, in this case we used "alpha" which is defined within the component "Ext.form.VTypes", so don't forget that.
Validations in Ext JS

Only alpha characters

Validate an e-mail

A common validation is the e-mail, let's assign the "VType" that corresponds to the field of email in our form as follows:
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		//… code removed for simplicity

		{fieldLabel:'Email',name:'email',vtype:'email'}, // validating an e-mail

//… code removed for simplicity
	]
});
Thanks to Ext JS we don't have to spend more than a minute to add that validation, now the form will look similar to the following screen when you enter a invalid e-mail.
Validations in Ext JS

Validation of an e-mail

Validate an URL

Let's see how to validate a Website address or "URL".
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		//… code removed for simplicity

		{fieldLabel:'Web site',name:'website',vtype:'url'}, //validating an URL

//… code removed for simplicity
	]
});
I'd like to emphasize that it also validates protocols such as "https" and "ftp".
Validations in Ext JS

Validation of an URL

Validation in the server

So far we have seen how to validate on the client side, but it is also important to validate on the server side, let's see how we can display the validation errors that are caused on the server. Ext JS has a feature that will save us a lot of time when we need to display the errors caused in the server, this feature will emphasize the exact area where and why the error was caused. To use this feature the server response should have the following format:
{
	success: false,
	msg: 'General message of the error',
	errors: {
		field: 'Message of the reason of the error',
		anotherFieldError: 'what caused the error?'
       }
}
After defining the error messages, we need to edit the file "simplevalidations.php" and generate some test failures.
$info = array(
	'success' => false,
	'msg' => 'There was an error saving the record',
	'errors' => array(
		'name' => $name.' is not an employee of this corporation',
		'email' => 'E-mail does not exist in the database',
		'comment' => 'The comment is to short'
	)
);
These fields are enough to accomplish the functionality we want, so just go ahead a refresh your browser and you will see something similar to the following image:
Validations in Ext JS

Displaying validations errors caused in the server side

With this we can see that although the client validations are correct, the information may be incorrect due to our business logic, in this example the name of the person should exist in our catalog of employees (hypothetical example).

Conclusions

The validations are very important, today we saw how to use the default validations and we learned how to display error messages that are generated on the server. As you can see it was very easy validating fields with Ext JS. If you have any questions or suggestions feel free to leave a comment on this post and don't forget to follow us on Twitter (@quizzpot) to be updated.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

4Comentarios

  • Avatar-12 gavarin daniel 17/02/2010

    json format for errors in validation server { "success" : false, "errors" : [ { "msg" : "This field is required", "id" : "field" } ] } { "success" : true, "data" : { field : "value" } }

    • Avatar-12 ccchai 12/04/2010

      Nice article. Where can I get a complete list of built in vtype ?? Also, the custom validations article does not touch on regular expression, do you mind to show an example on regex??

      • Avatar-1 Qazi 15/04/2012

        Fuck U.. Itz not work for me.. reupload your file.

        • Avatar-4 lav 04/09/2013

          please tell me regex with validation using sencha touch?

          Instructor del curso

          Crysfel3

          Autor: Crysfel Villa

          Software engineer with more than 7 years of experience in web development.

          Descarga Código Fuente Ver Demostración

          Regístrate a este curso

          Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

          Tendrás acceso a descargar los videos, códigos y material adicional.

          Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

          Llevarás un registro de tu avance.