Learning Ext JS 3

Custom validations Más videos

Descripción del tema

Many times it is necessary to create specific validations for our applications and are necessary to achieve the correct functionality, this tutorial explains how we can create "vtype's" to validate our ExtJS forms. In the previous tutorial we saw how to do common validations, today we will learn how to do personalized validations and we'll also see how to restrict the entry of characters in the text boxes. I'll invite you to test the demo of what we'll do in this tutorial.
Vtype in Ext JS

Form with personalized validations

Resources

Before we start the tutorial don't forget to download the resources, which only consist of two files: a HTML and JS; I have created a form and I put it inside of a window, so what you need to do is add the validations to some fields.

Display error messages

If you execute the resources at this moment you will see that three fields are required, and when you click on the button "save" you will see some errors in red (if you don't write anything in the text boxes), but only around the fields.
Vtype in Ext JS

No error messages

The user should receive enough information to know what is wrong and how to fix it, so what we need to do is show an error message, to do this we only need to write the following lines at the beginning of the method "init":
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
The first line allows to display floating messages when we position the mouse over the text box, on the second line we display an error icon on the side of the field.
Vtype in Ext JS

Displaying a floating message with the validation error

Validate the age of majority

In the "Date of birth" we're going to calculate how many years we have from the given date of birth to today and validate that is over 18 years. In the previous tutorial we saw how to use the "vtype's" that are included in the ExtJS framework, today we'll add more validations to the class "Ext.form.VTypes. The first thing we need to do is to extend the class like this:
Ext.apply(Ext.form.VTypes,{

	//in here we're going to define the validations

});
The next things we need to do is define the "vtype" like this:
Ext.apply(Ext.form.VTypes,{
	adult: function(val, field){
		try{
			var birth = field.getValue();
			var now = new Date();
			// The number of milliseconds in one year
			var ONE_YEAR = 1000 * 60 * 60 * 24 * 365;
		    	// Convert both dates to milliseconds
		    	var date1_ms = birth.getTime()
		    	var date2_ms = now.getTime()
		    	// Calculate the difference in milliseconds
		    	var difference_ms = Math.abs(date1_ms - date2_ms)
		    	// Convert back to years
		    	var years = difference_ms/ONE_YEAR;
			return years >= 18;
		}catch(e){
			return false;
		}
	},
	adultText: 'You are underage!', //error message
	adultMask: / /  //regexp to filter the characters allowed
});
First we defined the name that the "VType" will receive, in this case "adult", then we assign a function that receives two parameters: the contents of the field and the instance of the field that's being validated, within this function we will have the code to validate and it must return "true" when the captured value is correct or "false" when the value is incorrect. The next thing we need to do is define the text to display if the captured information is incorrect, we must remember that we have more validations within this object (Ext.form.VTypes), therefore to link the message with the function we only need to add the word "Text" at the end of the function name, in this case "adultText. Optionally we can define a filter to capture only the correct characters, in order to do that we need to define a mask with the appropriate regular expression.
adultMask: /[\d\/]/
The previous regular expression validates that the user can only enter digits and a slash, these characters are the only ones we need to enter a date in the format we have defined; please notice that the property is called "adultMask", we only added at the end the word "Mask" to relate it with the validation we created previously. Having defined the "vtype" we have to assign it to the field we need to validate, in this case the field "birth" of the form:
{xtype:'datefield',fieldLabel:'Date of birth',name:'birth',allowBlank:false,format:'d/m/Y',vtype:'adult'},
Vtype in ExtJS

Validating a date of birth (validating age of majority)

Validate a phone number

Now we will validate the format of a phone number, first we need to define the validation rules.
  • Must contain 10 digits, for example: 8192847135
  • It can only accept parentheses, dashes, spaces and numbers,for example: (81) 92 847 135, 81 92-847-135, (81) 92-847-135, 81 92 84 71 35, 8192847135
  • It should only contain characters defined previously.
With these rules we can now define the "vtype":
phone: function(value,field){
	return value.replace(/[ \-\(\)]/g,'').length == 10;
},
phoneText: 'Wrong phone number, please make sure it contains 10 digits',
phoneMask: /[ \d\-\(\)]/
The function defined in the property "phone" only removes the accepted characters (such as spaces, dashes, parentheses) leaving only the numbers, then validates that are ten digits; the mask accepts only the characters defined in the rules. Finally we need to assign the "vtype" to the form field that we need to validate.
{fieldLabel:'Phone number',name:'phone',vtype:'phone'},
Vtype in ExtJS

Validating a phone number

Validate a credit card

In this last example we will validate the number of a credit card. First, we need to define the validation rules to have a clear idea of what we need to do.
  • The number should have 16 digits, for example: 1234567891234567
  • We can only accept digits, spaces and dashes, for example: 1234 5678 9123 4567, 1234-5678-9123-4567
  • We should not accept any other character than the previous mentioned.
You can see that these rules are very similar to the phone, so we can do a copy / paste and modify the code to fit these requirements.
creditcard: function(value,field){
	return value.replace(/[ \-]/g,'').length == 16;
},
creditcardText: 'Wrong credit card number',
creditcardMask: /[ \d\-]/
I just made small changes because these rules are very similar, now we need to add the "vtype" to the field "credit":
{fieldLabel:'Credit card',name:'credit',vtype:'creditcard'},
Vtype in ExtJS

Validating a credit card

Conclusions

Today we learned how to create our own client-side validations, as you can see it was really easy. ExtJS provides us an easy way to create custom validations and even put a mask on our fields. If you have any question or suggestion feel free to leave a comment on this post. Don't forget to follow us on Twitter (@quizzpot) to be updated with the new tutorials we will post.

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

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.