Solved

Form validation with jquery - code performance

Posted on 2013-01-06
23
465 Views
Last Modified: 2013-01-08
Hello Experts.

With my modest knowledge of jquery I wrote this form that validates without page refresh. My question is if the code has any issues, I feel that I wrote too much code and that may have some flaws. Can you help me organizing this code better? Maybe there's a clever way to do it.

Thank you

//IsValidNIF function code (...)



$('form').on('submit', function() {


        var input = $('input');
	var info  = $('#infoSubmit');
	var inName = $('input#name-of-company');
	var inNif = $('input#nif');
        var inAi = $('input#annual-income');
        var inEmp = $('input#employees');


	var nameReg = /^\S.{0,58}\S$/;
        var aiReg   = /^([0-9]{3,15})$/;
        var empReg   = /^([0-9]{1,10})$/;




          if ( !nameReg.test( inName.val() ) ) {  

          	info.text('please enter a valid name');
          	inName.addClass('wrongInput');
          	inName.focus();
          
          } else if( !IsValidNIF( inNif.val() ) ) {

          	input.removeClass('wrongInput');
          	info.text('');
          	inNif.focus();

                info.text('please enter a valid nif');
                inNif.addClass('wrongInput');
                inNif.focus();

          } else if( !aiReg.test( inAi.val() ) ) {

                input.removeClass('wrongInput');
                info.text('');
                inAi.focus();

                info.text('please enter a valid annual income');
                inAi.addClass('wrongInput');
                inAi.focus();

          } else if( !empReg.test( inEmp.val() ) ) {

                input.removeClass('wrongInput');
                info.text('');
                inEmp.focus();

                info.text('please enter a valid number of employees');
                inEmp.addClass('wrongInput');
                inEmp.focus();               

          } else {

                input.removeClass('wrongInput');
                info.text('');


                $.post('save.php', $(this).serialize(), function() {
                        $(infoSubmit).text('Data submitted, thank you!');
                        inName.val('');
                        inNif.val('');
                        inAi.val('');
                        inEmp.val('');

                });

          }


        return false;


});

Open in new window

0
Comment
Question by:joao_c
  • 12
  • 6
  • 5
23 Comments
 
LVL 9

Expert Comment

by:abolinhas
Comment Utility
0
 

Author Comment

by:joao_c
Comment Utility
Thanks for the reply.

I would prefer to stay with this aproach instead of plugins. Just need to improve the code. For example, this only gives an error class to a field when I click submit. And also this repetition of if statements I'm sure that is not the best.

Anyone can help me to improve this?
0
 
LVL 9

Expert Comment

by:abolinhas
Comment Utility
this only gives an error class to a field when I click submit.
which input ?

Can you post your html form to ?
0
 

Author Comment

by:joao_c
Comment Utility
My html:


		<form id="myForm" action="#" method="get">
					
					<label for="name-of-company">Company Name:</label>
					<input type="text" name="name-of-company" value="" id="name-of-company" />

					<label for="annual-income">NIF:</label>
					<input type="text" name="nif" value="" id="nif" />	

					<label for="annual-income">Annual Income:</label>
					<input type="text" name="annual-income" value="" id="annual-income" />	

					<label for="employees">Employees:</label>
					<input type="text" name="employees" value="" id="employees" />	
					
					<input type="submit" name="submit" value="Submit" id="submitBtn"/>
		</form>

		<span id="infoSubmit"></span>

Open in new window

0
 

Author Comment

by:joao_c
Comment Utility
What I need here is a way to implement in-line validation. For example:

when I first click submit I get the errors, but I wanted to clean the error when the input was correct, instead of having to click submit again to see if there is any errors.

I know that there is a onchange event(?) , but now sure how to "mix" it with my submit event.

Thanks
0
 
LVL 11

Expert Comment

by:mcnute
Comment Utility
What you could do is to use the latest jquery availabel. For example according to this presentation on jquery performance the val() method often used in your code improved massivley from 1.4 to 1.6 in this example. Amongst a lot of other useful hints to improve performance.

I've tested your code on jsperf.com and did try to make more use of the chaining, but it seems quite performant already. No change in using the chaining method and your selectors are as simple as they could be. Almost no room for improvement at a first glance. If you want to compare modifications you do to the code you can edit the snippets here.
0
 

Author Comment

by:joao_c
Comment Utility
Thanks for the comments but maybe the title is not the best I could use. My follow-up question is really to make validation(display in-line errors/tips) when the user is typing. That's why I mentioned in the last comment the onchange event.

Need to explore this.
0
 
LVL 11

Expert Comment

by:mcnute
Comment Utility
why reinvent the wheel: use a powerful plugin.
0
 

Author Comment

by:joao_c
Comment Utility
mcnute, I have tried to use that plugin but then I have this function that validates a specific field of the form, and i dont understand how to incorporate in de the validate plugin. It's easy to replicate with regex's but with specific funtions I am not sure:

if( !IsValidNIF( inNif.val() ) ) {  >>> how to incorporate this in the plugin?

If you now how that would be a perfect solution for me.

Thanks
0
 
LVL 11

Expert Comment

by:mcnute
Comment Utility
You could add a custom validation rule like that:

$.validator.methods.IsValidNIF = function(value, element, param) {
    // Perform custom validation and return true or false
    return value === '' || /^([0-9]{10})$/.test(value);
};

Open in new window


and then something like that:
$("#myForm").validate({        
    rules: {
        nif: { 
            IsValidNif: true 
        }
    },
    messages: {
        nif: { 
            isValidNif: "Enter some information before proceeding" 
        }
    },
    submitHandler: function(form)
    {
        // do the work to submit this form
    }
});

Open in new window

0
 

Author Comment

by:joao_c
Comment Utility
And i put my function code (isvalidnif) where is now:

// Perform custom validation and return true or false
    return value === '' || /^([0-9]{10})$/.test(value);


??
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 11

Expert Comment

by:mcnute
Comment Utility
Put it all together into your submit function.
0
 

Author Comment

by:joao_c
Comment Utility
Hey mcnute, how can I display errors as a  tooltip on the right of the input?
0
 
LVL 11

Expert Comment

by:mcnute
Comment Utility
Just style it to like a tooltip in CSS.

#yourform label.error { your CSS directives here }

Open in new window

0
 

Author Comment

by:joao_c
Comment Utility
Ok, let me explain:

My html:

<form id="myForm" action="" method="post">
					
					<label for="nameCompany">Company Name:</label>
					<input type="text" name="nameCompany" value="" id="nameCompany" />

					<label for="nif">NIF:</label>
					<input type="text" name="nif" value="" id="nif" />

					<label for="annualIncome">Annual Income:</label>
					<input type="text" name="annualIncome" value="" id="annualIncome" />

					<label for="employees">Employees:</label>
					<input type="text" name="employees" value="" id="employees" />
					
					<input type="submit" name="submit" value="Submit" id="submitBtn"/>




			</form>

Open in new window



My css:

body {
	font-family: Calibri;
}

#myForm {
	/background: blue;
	/overflow: visible;

}






label {
	width: 120px;
	margin-right: 8px;
	float: left;
	text-align: right;
	color: blue;
}

input {
	display: block;
}




#submitBtn {
	margin-left: 225px;
	margin-top: 5px;
	overflow: visible;
}

Open in new window


And it renders like so:

form2
The problem is that the errors display on the bottom of the labels and inputs. I want to display the error messages on the right of the respective input.

Thanks
0
 
LVL 11

Expert Comment

by:mcnute
Comment Utility
If you expect that I will do all the styling for you, than you can wait a long time. I've already told you how to do it. The error messages are given a class of "error". So style these labels with the class error accordingly. So that they are on the right of your inputs. This is accomplished by adding to your stylesheet a class of error which you position accordingly. Probably with a float: right in combination with position: absolute/relative. But that's your job!

I hope I could help.
As I could see the validation and your custom function are already functioning.

P. s.: It's not a good policy to do the actual work for you, in that case you must hire us.
0
 

Author Comment

by:joao_c
Comment Utility
well, I did that float right and tried to position but somehow it's attached to the label and don't float to the right of the input.

Anyways, don't waste your time. I missunderstood EE purpose, I guess.
0
 
LVL 9

Expert Comment

by:abolinhas
Comment Utility
Hi João,

At this stage you still using your own validation script or the jquery validation plugin as mcnute propose ?

PS: I'm Portuguese to.
0
 

Author Comment

by:joao_c
Comment Utility
Olá abolinhas :)

I am using the validate plugin, struggling to make it work as I want.

I would like to implement some tooltips with fadein/fadeout on the right of the inputs to display errors, and also have some custom functions to validade some of the fields like the NIF one.

I just started learning jquery and want to implement it in this small project. Since the form is the main focus of the page i want it to behave properly and be user-friendly.

So far I have done what was needed, but since I have some more time to finish it I wanted to make it look "fancy". :D

My main job is in the 3D field, but you know that in our country we need to be versatile :D


Cheers
0
 
LVL 9

Expert Comment

by:abolinhas
Comment Utility
on the right of the inputs to display errors
#commentForm label.error, #commentForm input.submit {
margin-left: 10px;
width: auto;
display: inline;
}

Open in new window

Change commentForm to your form ID

My main job is in the 3D field
Which company you work ? I worked about 5 years in a 3D company in lisbon.
0
 

Author Comment

by:joao_c
Comment Utility
I ended up using <p> to separate the inputs instead of floats and the errors now display on the right as I wanted :)

Do you know how to implement a fadeToogle effect when the error display/hide?



I worked 2 years in Porto for "Akropolis"  till recently, doing productViz for medical equipments. You can see some images here (maya, mental ray). Now I am doing freelance work, but not easy these days to do 3D in Portugal.

You still do 3D? I use maya and arnold render mostly.
0
 
LVL 9

Accepted Solution

by:
abolinhas earned 500 total points
Comment Utility
Try this
http://stackoverflow.com/questions/7925368/how-to-fade-out-error-prompts-with-validation-engine-plug-in-for-jquery?answertab=active#tab-top


You still do 3D? I use maya and arnold render mostly.
Não, eu não trabalho em 3D. Eu era responsável por todo parque informatico dessa empresa (Arqui300 e Arqui300 Academy).
0
 

Author Comment

by:joao_c
Comment Utility
Try this
http://stackoverflow.com/questions/7925368/how-to-fade-out-error-prompts-with-validation-engine-plug-in-for-jquery?answertab=active#tab-top

Nice, I will have a look at it.

Não, eu não trabalho em 3D. Eu era responsável por todo parque informatico dessa empresa (Arqui300 e Arqui300 Academy).

Ah, eu pensei logo nessa empresa. Fazem grandes trabalhos de Archviz ;)
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now