[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 491
  • Last Modified:

Form validation with jquery - code performance

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
joao_c
Asked:
joao_c
  • 12
  • 6
  • 5
1 Solution
 
joao_cAuthor Commented:
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
 
abolinhasCommented:
this only gives an error class to a field when I click submit.
which input ?

Can you post your html form to ?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
joao_cAuthor Commented:
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
 
joao_cAuthor Commented:
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
 
mcnuteCommented:
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
 
joao_cAuthor Commented:
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
 
mcnuteCommented:
why reinvent the wheel: use a powerful plugin.
0
 
joao_cAuthor Commented:
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
 
mcnuteCommented:
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
 
joao_cAuthor Commented:
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
 
mcnuteCommented:
Put it all together into your submit function.
0
 
joao_cAuthor Commented:
Hey mcnute, how can I display errors as a  tooltip on the right of the input?
0
 
mcnuteCommented:
Just style it to like a tooltip in CSS.

#yourform label.error { your CSS directives here }

Open in new window

0
 
joao_cAuthor Commented:
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
 
mcnuteCommented:
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
 
joao_cAuthor Commented:
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
 
abolinhasCommented:
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
 
joao_cAuthor Commented:
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
 
abolinhasCommented:
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
 
joao_cAuthor Commented:
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
 
abolinhasCommented:
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
 
joao_cAuthor Commented:
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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 12
  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now