-1

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.

enter image description here

Can anyone help me out.

7
  • Have you even considered trying out something at your end first?
    – asprin
    May 30, 2014 at 9:53
  • your question is not very clear please consider to provide more info.. so we can help.
    – VK321
    May 30, 2014 at 9:54
  • yes asprin. i have mentioned some code above from my script. the code was working for a page which contain only one form. but when i got multiple forms and i added loop in script, it got worse. May 30, 2014 at 9:56
  • why you using javasript if you using php... you can validate by php.
    – VK321
    May 30, 2014 at 9:57
  • can you provide some example. i tried it using php but with loop i could not handle it. May 30, 2014 at 10:00

1 Answer 1

1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.