Jump to content

Form HELP! Validation & server side


jilana2

Recommended Posts

Hi! I need help! No other forum is helping me and it's a bit urgent.

I have searched all over the internet and tried over 30 different codes but I can't get this to work. Im very new to php and that probably why. 

 

What I want help with:

 

1. I want my form to be validated server side. When the name or message field is left empty a errormessage(please fill in name, please fill in message) should be shown above the form on the SAME page without reloading or redirecting. 

 

2. Check so that the email entered in the email field is a valid email and not just filled out.

 

3. If everything is filled out correctly the form should be sent and a message is displayed above the form just like the error-messages for the fields.

 

 

Php:

 

 
<?php
 
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient = "info@mydomain.com";
    $subject = "Via Webbkontakt";
    $formcontent = "Namn: $name <br/> Email: $email <br/> Telefon: $phone <br/><br/> Meddelande:<br/><br/> $message";
 
    $headers = "From: " ."MyDomain<info@mydomain.com>" . "\r\n";
    $headers .= "Reply-To: ". "$email" . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=utf-8\r\n";
 
 
 
    if(@mail($recipient, $subject, $formcontent, $headers))
    {
        echo "successful";
    }
    else
    {
        echo "error";
    }
 
 
 
?>
 
 
 
 
Html:
 
 
<form class="form" id="contactus" action="php/mail.php" method="post" accept-charset="UTF-8">
 
<label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>
 
<input name="name" value="" type="text" id="name">
 
<label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>
 
<input name="email" value="" type="text" id="email">
 
<label for="phonetag">Telefon</label>
 
<input name="phone" type="text" id="phone"  value="" />
 
<label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label>
 
<textarea name="message" id="message" value="" style="width: 87%; height: 200px;"></textarea>
                 
 <label class="placeholder"> </label>
 
<button class="submit" name="submit">Skicka</button>
 
 
</form>
Edited by jilana2
Link to comment
Share on other sites

If you want to do all these things without reloading the page, then you will need to look into using JavaScript and AJAX to submit the data to a server-side PHP script for validation.

 

Okej. I managed to solve the "success message" thing a day ago with the code below. Now how do I do the validation & php part. The user can disable javascript in there browser so I want things to be server sided to prevent spam.

 

<script>
 
$(function() {
 
 
            $('#contactus').submit(function (event) {
                event.preventDefault();
                event.returnValue = false;
                $.ajax({
                    type: 'POST',
                    url: 'php/mail.php',
                    data: $('#contactus').serialize(),
 
 
                    success: function(res) {
                        if (res == 'successful') {
                            $('#status').html('Det uppstod ett fel!').slideDown();
                        }
                        else {
                            $('#status').html('Tack! Ditt meddelande har skickat.').slideDown();
document.getElementById("contactus").reset();
                        } 
                    },
 
error: function(XMLHttpRequest, textStatus, errorThrown) {  
 
                        $('#status').html('Det uppstod ett fel!').slideDown();
                    }
                });
            });
        });
</script>
Link to comment
Share on other sites

You can do this in this way....

 

I'm writing only the php code...

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient = "info@mydomain.com";
    $subject = "Via Webbkontakt";
if(!$name)
    echo "Enter the name";
else if(!$email)
   echo "Enter the email";
else if(!$phone)
   echo "Enter the phone number';
else if(!$message)
     echo "Enter the message";
// then rest of of ur code....
?>

note: u cannot validate the email in server side... U need javascript to do that... In server side u can only check whether all the fields are filled or not....

 

Hope it helps......

Link to comment
Share on other sites

You can do this in this way....

 

I'm writing only the php code...

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient = "info@mydomain.com";
    $subject = "Via Webbkontakt";
if(!$name)
    echo "Enter the name";
else if(!$email)
   echo "Enter the email";
else if(!$phone)
   echo "Enter the phone number';
else if(!$message)
     echo "Enter the message";
// then rest of of ur code....
?>

note: u cannot validate the email in server side... U need javascript to do that... In server side u can only check whether all the fields are filled or not....

 

Hope it helps......

 

How do I make the echo show when clicking submit and disappear when the user corrects it?

Link to comment
Share on other sites

Okej. I managed to solve the "success message" thing a day ago with the code below. Now how do I do the validation & php part. The user can disable javascript in there browser so I want things to be server sided to prevent spam.

You can't do exactly what you want if JS is disabled. With JS disabled, the page has to reload in order for the validation to happen, and if there is an error you have to re-generate the form along with the error messages.

 

With JS enabled, you can submit the form data via AJAX for validation and then check the response to see if there was an error or if everything was successful. If successful, go ahead and submit the from normally.

 

Generally speaking if you want the page to work both ways the easiest thing to do is to handle what validation you can within JS without involving ajax at all, then if that passes let the form submit and do the validations also on the server-side. Considering your validations are fairly simple (field not empty, email is valid format) this would be the ideal way to go. You only really need ajax validation in order to handle things which cannot be checked with JS alone (such as for username availability, or duplicate emails, etc).

 

$('#contactus').submit(function (e){
   var errors=[];
   if ($('#name').val() == ''){
     errors.push('Please enter your name');
   }
   if ($('#message').val() == ''){
     errors.push('Please enter your message');
   }
   if (!is_valid_email($('#email').val())){  //Google for a JS email validation function and use it here
     errors.push('Please enter a valid email addres');
   }

   if (errors.length){
     alert(errors); //Implement some better method of showing the errors
     e.preventDefault();
   }
});
Link to comment
Share on other sites

You can't do exactly what you want if JS is disabled. With JS disabled, the page has to reload in order for the validation to happen, and if there is an error you have to re-generate the form along with the error messages.

 

With JS enabled, you can submit the form data via AJAX for validation and then check the response to see if there was an error or if everything was successful. If successful, go ahead and submit the from normally.

 

Generally speaking if you want the page to work both ways the easiest thing to do is to handle what validation you can within JS without involving ajax at all, then if that passes let the form submit and do the validations also on the server-side. Considering your validations are fairly simple (field not empty, email is valid format) this would be the ideal way to go. You only really need ajax validation in order to handle things which cannot be checked with JS alone (such as for username availability, or duplicate emails, etc).

 

$('#contactus').submit(function (e){
   var errors=[];
   if ($('#name').val() == ''){
     errors.push('Please enter your name');
   }
   if ($('#message').val() == ''){
     errors.push('Please enter your message');
   }
   if (!is_valid_email($('#email').val())){  //Google for a JS email validation function and use it here
     errors.push('Please enter a valid email addres');
   }

   if (errors.length){
     alert(errors); //Implement some better method of showing the errors
     e.preventDefault();
   }
});

 

 

Okey :)

I need the success and fail messages as well. Could you help I'm new to php and the form thing. If you could use my code and change it so that I can paste it in my documents you would be an angel. I need this to work soon :/

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.