Custom validations Más videos
Descripción del tema
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.No error messages
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.
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'},
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.
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'},
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.
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'},
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.
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.
4Comentarios
Lovely! works perfectly for phone #'s. Thankxxx!
Como valido un nif/cif. Alguna idea? Gracias de antemano
thank you.. its workng
Dear quizzpot.com admin, You always provide great examples and real-world applications, thank you for your valuable contributions.