joao_c
asked on
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
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;
});
ASKER
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?
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?
this only gives an error class to a field when I click submit.which input ?
Can you post your html form to ?
ASKER
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>
ASKER
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
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
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.
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.
ASKER
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.
Need to explore this.
why reinvent the wheel: use a powerful plugin.
ASKER
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
if( !IsValidNIF( inNif.val() ) ) { >>> how to incorporate this in the plugin?
If you now how that would be a perfect solution for me.
Thanks
You could add a custom validation rule like that:
and then something like that:
$.validator.methods.IsValidNIF = function(value, element, param) {
// Perform custom validation and return true or false
return value === '' || /^([0-9]{10})$/.test(value);
};
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
}
});
ASKER
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 );
??
// Perform custom validation and return true or false
return value === '' || /^([0-9]{10})$/.test(value
??
Put it all together into your submit function.
ASKER
Hey mcnute, how can I display errors as a tooltip on the right of the input?
Just style it to like a tooltip in CSS.
#yourform label.error { your CSS directives here }
ASKER
Ok, let me explain:
My html:
My css:
And it renders like so:
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
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>
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;
}
And it renders like so:
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
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.
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.
ASKER
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.
Anyways, don't waste your time. I missunderstood EE purpose, I guess.
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.
At this stage you still using your own validation script or the jquery validation plugin as mcnute propose ?
PS: I'm Portuguese to.
ASKER
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
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
on the right of the inputs to display errors
#commentForm label.error, #commentForm input.submit {
margin-left: 10px;
width: auto;
display: inline;
}
Change commentForm to your form IDMy main job is in the 3D fieldWhich company you work ? I worked about 5 years in a 3D company in lisbon.
ASKER
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.
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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 ;)
Demo:
http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
Download:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/