/    Sign up×
Community /Pin to ProfileBookmark

JQuery Form Validation using php functions

the intention is submit a form using jQuery AJAX on a PHP page with the form validation part done with JQuery. The code as it stands now is as follows:

The HTML form:

[code]
<form class=”contactus-contactform validate-form” action=” ” method=”post” enctype=”text/plain” autocomplete=”off”>
<label class=”label-input” for=”name”>Full name *</label>
<div class=”contactfld-input validate-input” data-validate = “Name is required”>
<input class=”input-fld” id=”name” type=”text” name=”name” placeholder=”Enter your name”>
<span class=”focus-input”>

</span>
</div>
<!– // contactfld-input –>

<label class=”label-input” for=”phone”>contact number *</label>
<div class=”contactfld-input validate-input” data-validate = “Valid telephone number is required”>
<input class=”input-fld” id=”phone” type=”text” name=”phone” placeholder=”Enter your contact number”>
<span class=”focus-input”>

</span>
</div>
<!– // contactfld-input –>

<label class=”label-input” for=”email”>Email address *</label>
<div class=”contactfld-input validate-input” data-validate = “Valid email is required: [email protected]”>
<input class=”input-fld” id=”email” type=”text” name=”email” placeholder=”Eg. [email protected]”>
<span class=”focus-input”>

</span>
</div>
<!– // contactfld-input –>

<label class=”label-input” for=”email”>Subject *</label>
<div class=”contactfld-input mailsubject”>
<select class=”input-fld subjectselect” id=”emailsubject” name=”” onchange=”” onclick=”return false;” id=””>
<option value=””>Choose …</option>
<option value=”Table Reservations”>Table Reservations</option>
<option value=”Bookings”>Bookings</option>
<option value=”Party Hall Enquiry”>Party Hall Enquiry</option>
<option value=”Party Hall Booking”>Party Hall Booking</option>
<option value=”Catering Enquiry”>Catering Enquiry</option>
<option value=”Catering Arrangments”>Catering Arrangments</option>
<option value=”Catering Services”>Catering Services</option>
<option value=”Menu Orders”>Menu Orders</option>
<option value=”Banqueting Service Enquiry”>Banqueting Service Enquiry</option>
<option value=”Banqueting Arrangments”>Banqueting Arrangments</option>
<option value=”Online Enquiry”>Online Enquiry</option>
<option value=”Online Orders”>Online Orders</option>
<option value=”Online Order Ammendment”>Online Order Ammendment</option>
<option value=”Thoughts and Feedback”>Thoughts &amp; Feedback</option>
<option value=”General Question”>General Question</option>
<option value=”Complaint”>Complaint</option>
</select>
<span class=”focus-input”>

</span>
</div>
<!– // contactfld-input –>

<div class=”add-informationrequired”>
<label class=”label-input” for=”tableno”>Table no/ Order Id </label>
<div class=”contactfld-input”>
<input class=”input-fld” id=”tableorder-idno” type=”text” name=”idno-tableorder” placeholder=””>
<span class=”focus-input”>

</span>
</div>
<!– // contactfld-input –>
</div>
<!– // add-informationrequired –>

<label class=”label-input” for=”message”>Message *</label>
<div class=”contactfld-input validate-input” data-validate = “Message is required”>
<textarea class=”input-fld” id=”message” name=”message” placeholder=”Type your message here…”></textarea>
<span class=”focus-input”>

</span>
</div>
<!– // contactfld-input –>

<div class=”container-contactform-submit-btn”>
<button class=”contactform-submit-btn submitmsgbtn”>
Send Message
</button>
<!– // contactform-submit-btn submitmsgbtn –>
</div>
<!– // container-contactform-submit-btn –>
</form>
<!– // contactus-contactform validate-form –>
[/code]

and the JQuery for the validation part

[code]

(function ($) {
“use strict”;
var input = $(‘.validate-input .input-fld’);

$(‘.validate-form’).on(‘submit’,function(){
var check = true;

for(var i=0; i<input.length; i++) {
if(validate(input[i]) == false){
showValidate(input[i]);
check=false;
}
}

return check;
});

$(‘.validate-form .input-fld’).each(function(){
$(this).focus(function(){
hideValidate(this);
});
});

function validate(input) {
if ($(input).attr(‘type’) == ’email’ || $(input).attr(‘name’) == ’email’) {
<?php
if (empty($_POST[“email”]) {
echo ‘<script type=”text/javascript”>’,
‘showValidate(input);’,
‘</script>’;
} else {
$email = $_POST[“email”];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo ‘<script type=”text/javascript”>’,
‘showValidate(input);’,
‘</script>’;
}
}
?>
} else {
if ($(input).val().trim() == ”) {
return false;
}
}
}
// function validate(input)

function showValidate(input) {
var thisAlert = $(input).parent();

$(thisAlert).addClass(‘alert-validate’);
}

function hideValidate(input) {
var thisAlert = $(input).parent();

$(thisAlert).removeClass(‘alert-validate’);
}
})(jQuery);
[/code]

but this for some reason throws the error: PHP Parse error: syntax error, unexpected ‘{‘ in /home/mnzsm9leak30/public_html/contact11.php on line 4757

which would be the line: if (empty($_POST[“email”]) within the function validate

could someone please give the function the once over with any pointers, ideas, or solution and yes i’m aware Icould have used a regex pattern but I opted to use php function and would prefer for it stay that way if possible

to post a comment
PHP

11 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJan 11.2020 — Well, the error is due to needing an additional ")" to close the if expression...but it looks odd to be to be outputting &lt;script&gt; tags inside of JavaScript code, so I'm not sure you won't still have problems after fixing that.
Copy linkTweet thisAlerts:
@nsathauthorJan 11.2020 — @NogDog#1612882 o yes but having rectified that, the form is still not validating or showing the showValidate function's message. Is there any way or approach you would take around this?
Copy linkTweet thisAlerts:
@NachfolgerJan 15.2020 — @nsath#1612966
  • 1. Are there any additional errors from PHP?

  • 2. Are there any additional errors from JavaScript/jQ

  • 3. Is jQuery making the XHR request?
  • Copy linkTweet thisAlerts:
    @SempervivumJan 15.2020 — I'm fairly shure that this cannot work:
    function validate(input) {
    if ($(input).attr('type') == 'email' || $(input).attr('name') == 'email') {
    &lt;?php
    if (empty($_POST["email"]) {
    echo '&lt;script type="text/javascript"&gt;',
    'showValidate(input);',
    '&lt;/script&gt;';
    } else {
    $email = $_POST["email"];
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo '&lt;script type="text/javascript"&gt;',
    'showValidate(input);',
    '&lt;/script&gt;';
    }
    }
    ?&gt;
    } else {
    if ($(input).val().trim() == '') {
    return false;
    }
    }
    }
    You are inserting a script tag into javascript. This should result in a syntax error. Your editor or the console when running the script should tell you.

    BTW: HTML5 provides built in form validation. No need to code it by Javascript:

    https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation
    Copy linkTweet thisAlerts:
    @codexcotechnologiesJan 15.2020 — Thank you all, valuable information
    Copy linkTweet thisAlerts:
    @nsathauthorJan 17.2020 — I've made a fair of alterations but as it stands the contact page still refreshes on submit whether the form is or is not filled in with no errors being thrown and no validation shown either the code now is as below:

    contactform.php
    <i>
    </i>&lt;form class="contactus-contactform validate-form" action=" " method="post" enctype="text/plain" autocomplete="off"&gt;
    &lt;label class="label-input" for="name"&gt;Full name *&lt;/label&gt;
    &lt;div class="contactfld-input validate-input" data-validate = "Name is required"&gt;
    &lt;input class="input-fld" id="name" type="text" name="name" placeholder="Enter your name"&gt;
    &lt;span class="focus-input"&gt; <br/>
    &lt;/span&gt;
    &lt;/div&gt;
    <br/>
    <i> </i> &lt;label class="label-input" for="phone"&gt;contact number *&lt;/label&gt;
    <i> </i> &lt;div class="contactfld-input validate-input" data-validate = "Valid telephone number is required"&gt;
    <i> </i> &lt;input class="input-fld" id="phone" type="text" name="phone" placeholder="Enter your contact number"&gt;
    <i> </i> &lt;span class="focus-input"&gt;
    <i> </i> &lt;/span&gt;
    <i> </i> &lt;/div&gt;
    <i> </i>
    <i> </i> &lt;label class="label-input" for="email"&gt;Email address *&lt;/label&gt;
    <i> </i> &lt;div class="contactfld-input validate-input" data-validate = "Valid email is required: [email protected]"&gt;
    <i> </i> &lt;input class="input-fld" id="email" type="text" name="email" placeholder="Eg. [email protected]"&gt;
    <i> </i> &lt;span class="focus-input"&gt;
    <i> </i> &lt;/span&gt;
    <i> </i> &lt;/div&gt;

    <i> </i> &lt;label class="label-input" for="email"&gt;Subject *&lt;/label&gt;
    <i> </i> &lt;div class="contactfld-input mailsubject validate-input" data-validate = "subject required"&gt;
    <i> </i> &lt;select class="input-fld subjectselect" id="emailsubject" name="subject" onchange="" onclick="return false;" id=""&gt;
    <i> </i> &lt;option value=""&gt;Choose ...&lt;/option&gt;
    <i> </i> &lt;option value="Table Reservations"&gt;Table Reservations&lt;/option&gt;
    <i> </i> &lt;option value="Bookings"&gt;Bookings&lt;/option&gt;
    <i> </i> &lt;option value="Party Hall Enquiry"&gt;Party Hall Enquiry&lt;/option&gt;
    <i> </i> &lt;option value="Party Hall Booking"&gt;Party Hall Booking&lt;/option&gt;
    <i> </i> &lt;option value="Catering Enquiry"&gt;Catering Enquiry&lt;/option&gt;
    <i> </i> &lt;option value="Catering Arrangments"&gt;Catering Arrangments&lt;/option&gt;
    <i> </i> &lt;option value="Catering Services"&gt;Catering Services&lt;/option&gt;
    <i> </i> &lt;option value="Menu Orders"&gt;Menu Orders&lt;/option&gt;
    <i> </i> &lt;option value="Banqueting Service Enquiry"&gt;Banqueting Service Enquiry&lt;/option&gt;
    <i> </i> &lt;option value="Banqueting Arrangments"&gt;Banqueting Arrangments&lt;/option&gt;
    <i> </i> &lt;option value="Online Enquiry"&gt;Online Enquiry&lt;/option&gt;
    <i> </i> &lt;option value="Online Orders"&gt;Online Orders&lt;/option&gt;
    <i> </i> &lt;option value="Online Order Ammendment"&gt;Online Order Ammendment&lt;/option&gt;
    <i> </i> &lt;option value="Thoughts and Feedback"&gt;Thoughts &amp;amp; Feedback&lt;/option&gt;
    <i> </i> &lt;option value="General Question"&gt;General Question&lt;/option&gt;
    <i> </i> &lt;option value="Complaint"&gt;Complaint&lt;/option&gt;
    <i> </i> &lt;/select&gt;
    <i> </i> &lt;span class="focus-input"&gt;
    <i> </i> &lt;/span&gt;
    <i> </i> &lt;/div&gt;
    <i> </i>
    <i> </i> &lt;script type="text/javascript"&gt;
    <i> </i> $(document).ready(function() {
    <i> </i> $('#emailsubject').change(function() {
    <i> </i> if (($(this).val() == 'Online Enquiry') || ($(this).val() == 'Online Orders') || ($(this).val() == 'Online Order Ammendment') || ($(this).val() == 'Complaint')) {
    <i> </i> $(".add-informationrequired").show();
    <i> </i> } else {
    <i> </i> $(".add-informationrequired").hide();
    <i> </i> }
    <i> </i> });
    <i> </i> });
    <i> </i> &lt;/script&gt;

    <i> </i> &lt;div class="add-informationrequired"&gt;
    <i> </i> &lt;label class="label-input" for="tableno"&gt;Table no/ Order Id &lt;/label&gt;
    <i> </i> &lt;div class="contactfld-input"&gt;
    <i> </i> &lt;input class="input-fld" id="tableorder-idno" type="text" name="idno-tableorder" placeholder=""&gt;
    <i> </i> &lt;span class="focus-input"&gt;
    <i> </i> &lt;/span&gt;
    <i> </i> &lt;/div&gt;

    <i> </i> &lt;/div&gt;
    <i> </i>
    <i> </i> &lt;label class="label-input" for="message"&gt;Message *&lt;/label&gt;
    <i> </i> &lt;div class="contactfld-input validate-input" data-validate = "Message is required"&gt;
    <i> </i> &lt;textarea class="input-fld" id="message" name="message" placeholder="Type your message here..."&gt;&lt;/textarea&gt;
    <i> </i> &lt;span class="focus-input"&gt;
    <i> </i> &lt;/span&gt;
    <i> </i> &lt;/div&gt;
    <i> </i>
    <i> </i> &lt;div class="container-contactform-submit-btn"&gt;
    <i> </i> &lt;button class="contactform-submit-btn submitmsgbtn" onClick="validateContactForm();"&gt;
    <i> </i> Send Message
    <i> </i> &lt;/button&gt;
    <i> </i> &lt;/div&gt;
    <i> </i> &lt;/form&gt;


    the processing and validation is as below:

    <i>
    </i> function validateContactForm() {
    var check;
    check = validateContactForm();
    if(check) {
    jQuery.ajax({
    url: "composeContactMessageMail.php", data:'name='+$("name").val()+'&amp;phone='+$("phone").val()+'&amp;email='+$("email").val()+'&amp;subject='+$(subject).val()+'&amp;idno-tableorder='+$(idno-tableorder).val()+'&amp;message='+$(message).val(),
    type: "POST",
    success:function(data){
    $("#mail-status").html(data);
    },
    error:function (){}
    });
    }
    }
    (function ($) {
    "use strict";
    var input = $('.validate-input .input-fld');
    $('.validate-form').on('submit',function(){
    var check = true;
    for(var i=0; i&lt;input.length; i++) {
    if(validate(input[i]) == false){
    showValidate(input[i]);
    check=false;
    }
    }
    return check;
    });
    $('.validate-form .input-fld').each(function(){
    $(this).focus(function(){
    hideValidate(this);
    });
    });
    function validateContactForm(input) {
    if($(input).attr('type') == 'email' || $(input).attr('name') == 'email') {
    if($(input).val().trim().match(/^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(]?)$/) == null) {
    return false;
    }
    }
    else {
    if($(input).val().trim() == ''){
    return false;
    }
    }
    }
    function showValidate(input) {
    var thisAlert = $(input).parent();
    $(thisAlert).addClass('alert-validate');
    }
    function hideValidate(input) {
    var thisAlert = $(input).parent();
    $(thisAlert).removeClass('alert-validate');
    }
    });


    and the composing of handling of the message is done by the following:

    composeContactMessageMail.php

    <i>
    </i>&lt;?php
    $toEmail = " "; //insert to email address

    $mailHeaders = "From: " . $_POST["name"] . "&lt;". $_POST["email"] ."&gt;rn";
    if(mail($toEmail, $_POST["phone"], $_POST["email"], $_POST["subject"], $_POST["idno-tableorder"], $_POST["message"], $mailHeaders)) {
    print "&lt;p class='success'&gt;Contact Mail Sent.&lt;/p&gt;";
    } else {
    print "&lt;p class='Error'&gt;Problem in Sending Mail.&lt;/p&gt;";
    }
    ?&gt;


    I can't tell what's wrong and need some ideas or even better a solution or way round this
    Copy linkTweet thisAlerts:
    @NachfolgerJan 18.2020 — @nsath#1613282

    Either I've missed it, or you've made no effort to prevent default form submission.

    Replace this:
    ``<i>
    </i>&lt;form class="contactus-contactform validate-form" action=" " method="post" enctype="text/plain" autocomplete="off"&gt;<i>
    </i>
    `</CODE>
    With:
    <CODE>
    `<i>
    </i>&lt;form class="contactus-contactform validate-form" action=" " method="post" enctype="text/plain" autocomplete="off" onsubmit="return false"&gt;<i>
    </i>
    ``
    Copy linkTweet thisAlerts:
    @nsathauthorJan 18.2020 — @Nachfolger#1613283

    ok fair enough I've made replacement as you've pointed out but that's not much difference is there? it just prevent the data being submitted until after validation has completed as far I understand
    Copy linkTweet thisAlerts:
    @NachfolgerJan 18.2020 — @nsath#1613285

    Correct, but you're submitting the form via AJAX, no? So you shouldn't be using the native functionality anyway. This is the cause of it "refreshing" regardless of the form being filled out or not.

    That was issue #2. As for issue #1 (the original reason for posting), what debugging have you done? We can't be expected to try and recreate your website just to test for issues; Is it now submitting the XHR validation request?
    Copy linkTweet thisAlerts:
    @nsathauthorJan 18.2020 — @Nachfolger#1613286

    issue 1 fair enough did not know that that was cause of it refreshing

    issue 2 no there is xhr validation request being made

    p.s. I'm pretty much a beginner as you can probably tell and I'm learning as I go along
    Copy linkTweet thisAlerts:
    @nsathauthorJan 22.2020 — @nsath#1613322

    ok now I've ammended it from the last time and now it logs an XHR as it shows on the network console but no mail is being sent and from the error log i'm getting the error

    [22-Jan-2020 03:35:26 UTC] PHP Notice: Undefined index: subject in /home/mnzsm9leak30/public_html/composemessage.php on line 4

    which is the subject being selected from select option which i'm unsure of how assign the selected option



    <i>
    </i>var subject = $('select[name=subject').val();


    for the below:

    <i>
    </i>&lt;select class="input-fld subjectselect" id="emailsubject" name="subject" onchange="" onclick="return false;" id=""&gt;
    &lt;option value=""&gt;Choose ...&lt;/option&gt;
    &lt;option value="Table Reservations"&gt;Table Reservations&lt;/option&gt;
    &lt;option value="Bookings"&gt;Bookings&lt;/option&gt;
    &lt;option value="Party Hall Enquiry"&gt;Party Hall Enquiry&lt;/option&gt;
    &lt;option value="Party Hall Booking"&gt;Party Hall Booking&lt;/option&gt;
    &lt;option value="Catering Enquiry"&gt;Catering Enquiry&lt;/option&gt;
    &lt;option value="Catering Arrangments"&gt;Catering Arrangments&lt;/option&gt;
    &lt;option value="Catering Services"&gt;Catering Services&lt;/option&gt;
    &lt;option value="Menu Orders"&gt;Menu Orders&lt;/option&gt;
    &lt;option value="Banqueting Service Enquiry"&gt;Banqueting Service Enquiry&lt;/option&gt;
    &lt;option value="Banqueting Arrangments"&gt;Banqueting Arrangments&lt;/option&gt;
    &lt;option value="Online Enquiry"&gt;Online Enquiry&lt;/option&gt;
    &lt;option value="Online Orders"&gt;Online Orders&lt;/option&gt;
    &lt;option value="Online Order Ammendment"&gt;Online Order Ammendment&lt;/option&gt;
    &lt;option value="Thoughts and Feedback"&gt;Thoughts &amp;amp; Feedback&lt;/option&gt;
    &lt;option value="General Question"&gt;General Question&lt;/option&gt;
    &lt;option value="Complaint"&gt;Complaint&lt;/option&gt;
    &lt;/select&gt;


    i've tried both of the below which stills throws the same error referred from various stackoverflow posts

    <i>
    </i>$('#emailsubject').on('change', function() {
    var subject = $('#emailsubject option:checked').val();
    });
    and

    var subject = var subject = $("select[name=subject] option:selected").val();

    any ideas?
    ×

    Success!

    Help @nsath spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.24,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...