Form validation inside a loop in php - javascript

I have a commenting system in PHP, in which there is loop to fetch articles. every article has a comment form which needs to be validated for null values.
Now problem is there is no limit to the number of these forms and ID of each form is coming from database. I want to validate each form but without writing the script multiple times.
How can i validate the form field for null value without writing script again & again.
Can i create a loop kind of thing in my script which check the field for null values.
My script is like this -
function validatecomments()
{
nums = ["1", "2", "3", "4"];
text = "commentform"; //form id is like this - commentform1, commentform2, ...
for (var i = 1; i < nums.length; i++) {
text = text + nums[i]; //to create it like form id
if (document.text.comment_emp_id.value=="")
{
alert("Please enter the Employee ID");
document.text.comment_emp_id.focus();
return false;
}
if (document.text.comment.value=="")
{
alert("Please give some Comments");
document.text.comment.focus();
return false;
}
}
}
this is snapshot of the comment form. here are 2 forms with POST button. Problem is i have a number of such forms in a page and i have to check them for null values. I am being forced to write script code multiple times.
Can anyone help me out.

you are not sending correct value to the script. try this
<form name="commentform<?php echo $your_id?>" action="" onSubmit="return validatecomments(this);" method="post">
in your script
function validatecomments(f)
{
if (f.elements['comment_emp_id'].value=="")
{
alert("Please enter the Employee ID");
f.elements['comment_emp_id'].focus();
return false;
}
else if (f.elements['comment'].value=="")
{
alert("Please give some Comments");
f.elements['comment'].focus();
return false;
}
}
May be it helps you.

Related

Two text fields, only one required to be filled (either)

So I have two fields in my webpage, one for telephone number and the other for email address, I need to make either one of them required to be filled by using JavaScript NOT jQuery. Most of the answers I found here are for jQuery, any solutions with JavaScript would be much appreciated. Thanks!
function User_one(){
var phone = document.getElementById('PhoneText2').value;
var mail = document.getElementById('EmailText1').value;
if (phone && mail == ""){
alert("An error occurred.");
}else{
return false;
}
}
Update with actual code
Here's how I'd do it
(function () {
document.getElementById('myForm').addEventListener('submit', function(event){
// Get the length of the values of each input
var phone = document.getElementById('PhoneText2').value.length,
email = document.getElementById('EmailText1').value.length;
// If both fields are empty stop the form from submitting
if( phone === 0 && email === 0 ) {
event.preventDefault();
}
}, false);
})();
Since you haven't supplied any code for us to work with, I'll answer in pseudo-code:
On form submission {
If (both telephone and email is empty) {
throw validation error
}
otherwise {
submit the form
}
}
If you show me your code I'll show you mine :-)

Focus on first invalid text field after form validation

I have a pretty standard HTML form in which I collect user input. I have a submit button that will run a JavaScript function (onClick) that in turn validate the data entered by the users.
The function looks like this:
function validateForm()
{
var isValid = true;
var txtFirstname = document.getElementById("firstName").value;
var txtLastname = document.getElementById("lastName").value;
(etc...)
/*Validate First Name*/
if(txtFirstname.length <= 0){
document.getElementById("lblFirstName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblFirstName").innerHTML="";
document.getElementById("firstName").value = txtFirstname;
}
/*Validate last Name*/
if(txtLastname.length <= 0){
document.getElementById("lblLastName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblLastName").innerHTML="";
document.getElementById("lastName").value = txtLastname;
}
(etc...)
if(isValid){
document.formX.submit();
}
else{
return false
}
}
My question is: how can I set the focus on the first "invalid" textbox after the function has validated the form?
Thanks,
Eric
i search 4 it & find a better popular solution :
`$("#"+document.querySelectorAll(":invalid")[1].id).focus();`
it's work for me. note that index of first invalid input in Firefox is 1 not 0. because of in FF the form is invalid and count, when an invalid input exist.
It would be cleaner if you functionally decomposed your validation. Then you could have a variable called "firstInvalidField" which is initially set to null. Upon invalidation of a field, check to see if firstInvalidField is null, if it is, set it to the textBox in question. If it is not null, skip over the code.
After the validation is complete, if the firstInvalidField variable is not null, call .focus() on it.

Alert if form is empty

How do I check if the whole form is empty and alert it? The form should be able to send even if there's a few empty inputs.
Edit:
Maybe I should've said that it's suppose to be JavaScript or jQuery.
And a better description:
I've got a form with one part that contains 10 input fields, you only have to fill out one.
The other part you only have to fill out name and phone or email but it's 4 fields you could fill with info.
And at last a checkbox making sure the user knows he or she didn't fill out the whole form.
I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.
Here is quick and dirty way using pure JavaScript:
function checkForm​(oForm) {
for (var i = 0; i < oForm.elements.length; i++) {
if (GetElementValue(oForm.elements[i]).length > 0)
return true;
}
alert("all empty");
return false;
}
function GetElementValue(element) {
if ((element.type === "checkbox" || element.type === "radio") && element.checked === false)
return "";
return element.value;
}
​Live test case.
create a validate method like this in JS (extend the Switch for other form Elements like radio or checkbox inputs):
function validateForm(domForm) {
var elements = domForm.elements;
var hasData = false;
var isAEmptyString = function(string) {
if(string) {
return string.length() == 0;
}
return true;
};
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
switch(element.tagName.toLowerCase()) {
case 'textarea':
if(!isAEmptyString(element.innerHTML)) {
return true;
}
break;
case 'input':
if(!isAEmptyString(element.value)) {
return true;
}
break;
case 'select':
if(element.selectedIndex >= 0) {
return true;
}
break;
}
}
return false;
};
you can call it in your form onSubmit handler
<form onsubmit="return validateForm(this);">
<textarea name="a"></textarea>
<input type="text" name="b"></input>
<select name="c">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<input type="submit" />
</form>
I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.
If that is the case just put a boolean check in your code
var haveAnyErrorsTriggered = false;
// loop through fields and if any are empty change the haveAnyErrorsTriggered to true
// then
if(haveAnyErrorsTriggered){alert("One or more fields are empty.");}
if you want to check if the whole form is empty, just do the opposite
var isAtLeastOneFieldFull = false;
// loop through fields and if any are not empty change the isAtLeastOneFieldFull to true
// then
if(!isAtLeastOneFieldFull){alert("all the fields are empty");}
You are talking about Javascript form validation. Create a Javascript function (called say validateForm) that validates the fields in your form, and pops up an alert if it detects an error. It should return true if the form is to be submitted, and false if there is an error. Then in the your HTML form tag, add the clause onsubmit="return validateForm()", where validateForm is the name of your function.
Maybe the form fields listener example I once cooked in this jsfiddle can help you further? Note that client side validation will never be enough. Anyone can tamper with the javascript in your page, so you allways have to validate a form server side too.

Javascript Validation Form

I am working with a form that has a catcha image. When a user fills out the form, and presses submit ( and only when the captcha number is wrong) the fields are reset or cleared. How can I prevent this from happening?
If a visitor fills out the form, presses submit, the expected behaviour is theform is submitted, or if the captch number is wrong, retain the information that the visitor had input in the fields and ask the visitor to fill in the correct captcha number...
Here is the js:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
When you want to prevent the default behaviour you've to use a callback function like this:
function onsubmit_handler(evt) {
if (/* validation is ok */) {
return true;
}
else { /* validation is not ok */
evt.preventDefault();
return false;
}
}
yourfom.onsubmit = onsubmit_handler;
Am I correct in believing that the captcha is validated (only) on the server after a successful validation by the JS (i.e., not via an Ajax call in the form submission event handler)? Am I further correct in believing that you're doing a true HTML form submission instead of an Ajax form submission in the background?
If both of those are true, then the problem probably isn't in your JavaScript at all (I say "probably" only because you could conceivably have a JS function that clears all the form fields on load or something like that). You're submitting the form to the server, the server looks at the captcha, sees that the answer is wrong, and displays the form again -- with blank values. You need to change your server code to include the user's previous answers as value attributes (or selected options or whatever as appropriate for the element type) when it writes the form after a server-side validation failure.

Javascript form validation - multiple form fields larger than 0

function negativeValues(){
var myTextField = document.getElementById('digit');
if(myTextField.value < 0)
{
alert("Unable to submit as one field has a negative value");
return false;
}
}
Above is a Javascript piece of code where every time a field id 'digit' has a value that's less than 0, than an alert box appears either onsubmit or onclick in the submit button.
There are about 50 fields in the form that should be considered 'digit' fields where they shouldn't be anything less than 0. What should I change with this Javascript to ensure that all 'digit' like fields have this alert box pop up?
I cannot use jquery/mootools for validation - it has to be flat Javascript.
Thanks.
var form = document.forms[0]; // first form in the document
form.onsubmit = function () {
for (var i=0; i<this.elements.length; i++)
if (Number(this.elements[i].value) < 0) {
alert("Unable to submit as one field has a negative value"); // complain
return false; // and prevent submission
}
}
Do not give ID="digit", ids need to be unique. Instead give a class="digit" or name="digit[]" which in PHP will give you an array on the server.
Here is a typical validation using forms access
function validate(theForm) {
var el = theForm.elements;
for (var i=0,n=el.length;i<n;i++) {
if (el[i].className=="digit" && parseInt(el[i].value,10)<0) {
alert('This field must contain a value > 0');
el[i].focus();
return false;
}
}
return true; // allow submission
}
assuming
<form onsubmit="return validate(this)">
Alternatives for the className== would be
if (el[i].className.indexOf('digit')!=-1
if the className could be manipulated from elsewhere.
You can use ID="digit1" ID="digit2" and
if (el[i].id.indexOf('digit')==0

Categories