Jump to content
Nic727

Form validation help (regex and PHP)

Recommended Posts

Thank you. Typing mistake is annoying because you can re-read the same thing multiple time without seeing the mistake hahaha.

About the Required, I'm just thinking if it's not a bad move to remove the required attribute since it's a good HTML5 attribute. One way I could use that + JS is if I remove my submit function and make it a click function when clicking on the "submit" button. Like that it doesn't send any information to the browser yet and can add the submit() after my validation.

Almost finished the Javascript part. Just a little issue that make the form submit. I know that I need something between my validation and my submit .ajax, but I don't know why or how.

$("#ajax-contact").submit(function(event) {
    
    event.preventDefault();

    // Get the form.
    var form = $("#ajax-contact");
     
    // Get the messages div.
    var formMessages = $("#form-messages");
    var prenomMessage= $("#prenom-message");
    var nomMessage= $("#nom-message");
    var emailMessage= $("#email-message");
    var sujetMessage= $("#sujet-message");
    var messageMessage= $("#message-message");

    // TODO
    // Serialize the form data.
    var formData = form.serialize();

    // Get the inputs
    var $prenom = $("#prenom");
    var $nom = $("#nom");
    var $email = $("#courriel");
    var $sujet = $("#sujet");
    var $message = $("#message");
    // Regex              
    var regex1 = /[^\d\W]{2,20}[\-\s\']{0,1}/i;
    
    // Testing Regex
    if(regex1.test($prenom.val())==false){
        $prenom.css({"border-color":"red"});
        prenomMessage.addClass('error');
        prenomMessage.text("Votre prénom est requis ou est invalide");
    }else{
        $prenom.css({"border-color":""});
        prenomMessage.removeClass('error');
    }
    if(regex1.test($nom.val())==false){
        $nom.css({"border-color":"red"});
        nomMessage.addClass('error');
        nomMessage.text("Votre nom est requis ou est invalide");
    }else{
        $nom.css({"border-color":""});
        nomMessage.removeClass('error');
    }
    if(!$.trim($email.val()).length){
        $email.css({"border-color":"red"});
        emailMessage.addClass('error');
        emailMessage.text("Votre adresse email est requise ou est invalide");
    }else{
        $email.css({"border-color":""});
        emailMessage.removeClass('error');
    }
    if(!$.trim($sujet.val()).length){
        $sujet.css({"border-color":"red"});
        sujetMessage.addClass('error');
        sujetMessage.text("Un sujet est requis");
    }else{
        $sujet.css({"border-color":""});
        sujetMessage.removeClass('error');
    }
    if(!$.trim($message.val()).length){
        $message.css({"border-color":"red"});
        messageMessage.addClass('error');
        messageMessage.text("Un message est requis");
    }else{
        $message.css({"border-color":""});
        messageMessage.removeClass('error');
    }
                 
        // Submit the form using AJAX.
        //...
}

That's so long...

 

But if I add the same kind of validation to my PHP (server side), will it not overwrite what I did in Javascript?

Edited by Nic727

Share this post


Link to post
Share on other sites

PHP validation is a must, JavaScript validation gives a quicker user friendly option without reloading of page that PHP would require.

Once the passing of validation in JavaScript is done, the validation through PHP should be instant, as all validation requirements have already been done through JavaScript.

Share this post


Link to post
Share on other sites

Ok thank you.

 

I also found out how to make it works. Is it correct like that or I can make it shorter?

$("#ajax-contact").submit(function(event) {
    
    event.preventDefault();

    // Get the form.
    var form = $("#ajax-contact");
     
    // Get the messages div.
    var formMessages = $("#form-messages");
    var prenomMessage= $("#prenom-message");
    var nomMessage= $("#nom-message");
    var emailMessage= $("#email-message");
    var sujetMessage= $("#sujet-message");
    var messageMessage= $("#message-message");

    // TODO
    // Serialize the form data.
    var formData = form.serialize();

    // Get the inputs
    var $prenom = $("#prenom");
    var $nom = $("#nom");
    var $email = $("#courriel");
    var $sujet = $("#sujet");
    var $message = $("#message");
    // Regex              
    var regex1 = /[^\d\W]{2,20}[\-\s\']{0,1}/i;
    
    // Testing Regex
    if(regex1.test($prenom.val())==false){
        $prenom.css({"border-color":"red"});
        prenomMessage.addClass('error');
        prenomMessage.text("Votre prénom est requis ou est invalide");
    }else{
        $prenom.css({"border-color":""});
        prenomMessage.removeClass('error');
    }
    if(regex1.test($nom.val())==false){
        $nom.css({"border-color":"red"});
        nomMessage.addClass('error');
        nomMessage.text("Votre nom est requis ou est invalide");
    }else{
        $nom.css({"border-color":""});
        nomMessage.removeClass('error');
    }
    if(!$.trim($email.val()).length){
        $email.css({"border-color":"red"});
        emailMessage.addClass('error');
        emailMessage.text("Votre adresse email est requise ou est invalide");
    }else{
        $email.css({"border-color":""});
        emailMessage.removeClass('error');
    }
    if(!$.trim($sujet.val()).length){
        $sujet.css({"border-color":"red"});
        sujetMessage.addClass('error');
        sujetMessage.text("Un sujet est requis");
    }else{
        $sujet.css({"border-color":""});
        sujetMessage.removeClass('error');
    }
    if(!$.trim($message.val()).length){
        $message.css({"border-color":"red"});
        messageMessage.addClass('error');
        messageMessage.text("Un message est requis");
    }else{
        $message.css({"border-color":""});
        messageMessage.removeClass('error');
    }
    if(regex1.test($prenom.val())==true && regex1.test($nom.val())==true && $.trim($email.val()).length && $.trim($sujet.val()).length && $.trim($message.val()).length){
        // Submit the form using AJAX.
            $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: formData,
            success: function(response) {
                // Make sure that the formMessages div has the 'success' class.
                formMessages.removeClass('error');
                formMessages.addClass('success');
     
                // Set the message text.
                formMessages.text(response);
     
                // Clear the form.
                $('#prenom').val('');
                $('#nom').val('');
                $('#courriel').val('');
                $('#sujet').val('');
                $('#message').val('');
            },
            error: function(data) {
                // Make sure that the formMessages div has the 'error' class.
                formMessages.removeClass('success');
                formMessages.addClass('error');
    
               // Set the message text.
               if (data.responseText !== '') {
                    formMessages.text(data.responseText);
                } else {
                    formMessages.text('Oops! An error occured and your message could not be sent.');
                }
            }
        })
    }                                   
})

I added the if statement that verify if everything is true or have a length higher than 0 and included the ajax inside.

Now need to add my website on the server and test some PHP codes. Now with PHP validation, just a little question, is it possible to change styling via PHP? For example, if someone remove JavaScript and I also want him to have border-color in red if false or show a message in my formMessages div? I guess the the message showing in my div is related to response and data.responseText here, but it still Javascript lol.

Share this post


Link to post
Share on other sites

You just need to create a PHP script to validate, and return a specific message for the error that relates to an input if validation fails. Check if specific error is not blank, then you can add a specific class  or styling attribute, as you already have for JavaScript to represent that there was an error. You can either validate on same php form page, until it passes validation then send to different page for further processing.

Share this post


Link to post
Share on other sites
6 hours ago, dsonesuk said:

You just need to create a PHP script to validate, and return a specific message for the error that relates to an input if validation fails. Check if specific error is not blank, then you can add a specific class  or styling attribute, as you already have for JavaScript to represent that there was an error. You can either validate on same php form page, until it passes validation then send to different page for further processing.

ok, because for now I have that :

// Check that data was sent to the mailer.
        if (empty($prenom) || empty($nom) || empty($courriel) || empty($suj) || empty($message) || !filter_var($courriel, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

If I had the same if as in Javascript, but for the PHP validation, is it a http_response_code(400) or it's another code?

Also, I guess I can't actually change my border colors via the php code right? Since I can't retrieve input and add css via the php file...

 

Thank you

Edited by Nic727

Share this post


Link to post
Share on other sites

That is the status code for AJAX, you might be able to still use this as an unvalidated identifier, if not valid you have to on validating on email page, set up sessions to take present values and error messages for those empty inputs, then redirect using to header() back to the form page and read those sessions there.

Share this post


Link to post
Share on other sites

Thank you.

 

It's now resolved, but just one thing. Is it normal that my regex is a weird color like that? Just want to make sure it will works, but other than that everything works fine now!

1529272777-sketch.png

Edited by Nic727

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×