0

My form needs to validate using js and alert any errors then go back to the form with the input values present so they can fix it before re-submitting. Once the validation passes it should redirect to a php "thank you" page. The validation logic is working correctly however after the error alerts it redirects to the php page prematurely.

My form HTML:

<form method = "post" name= "account" action= "validated.php" target="_blank">
            <div>
                <label for="fname"><span class="red">*</span> First Name:</label><br>
                <input type="text" id="fname" name="fname" size="40" required><br>
                <label for="lname">Last Name:</label><br>
                <input type="text" id="lname" name="lname" size="40">
            </div>
            <div>
                <label for="bdate">Birth Date:</label><br>
                <input type="text" id="bdate" name="bdate" placeholder="dd/mm"><br>
                <label for="email"><span class="red">*</span> Email Address:</label><br>
                <input type="email" id="email" name="email" size="40" placeholder="mymail@mymail.com" required>
            </div>
            <div>
                <p id="interests">Product Interests:</p>
                <div class= "pref">
                    <input type="checkbox" class="preferences" name="interests[]" value="donuts">
                    <label for="donuts">Donuts</label>
                </div>
                <div class= "pref">
                    <input type="checkbox" class="preferences" name="interests[]" value="vanilla slice">
                    <label for="vanillaSlice">Vanilla Slice</label>
                </div>                      
                <div class= "pref">
                    <input type="checkbox" class="preferences" name="interests[]" value="randy tarts">                      
                    <label for="randyTarts">Randy Tarts</label>
                </div>
                <div class= "pref">
                    <input type="checkbox" class="preferences" name="interests[]" value="custard tarts">
                    <label for="custardTarts">Custard Tarts</label>
                </div>
                <div class= "pref">
                    <input type="checkbox" class="preferences" name="interests[]" value="raspberry cheesecake">
                    <label for="raspberryCheesecake">Raspberry Cheesecake</label>
                </div>
                <div class= "pref">
                    <input type="checkbox" class="preferences" name="interests[]" value="applecake slice">
                    <label for="appleCakeSlice">Applecake Slice</label>
                </div>                      
            </div>
            <div>
                <input id="submit" type="submit" value= "Submit" name="submit" onclick="validate()"></input>
            </div>

My js code:

var fname, bdate, email;

function validate(){
// Required first name
fname = document.getElementById("fname").value;
try{
    if (fname == "") throw "You have not given your first name.";
}
catch(err) {
alert(err);
console.error(err);
}

// valid date format
bdate = document.getElementById("bdate").value;
var contains = bdate.indexOf("/");
var day = bdate.slice(0, 2);
var month = bdate.slice(3); 
try{
    if (contains != 2 && bdate !== "") throw "The date must be in the following format 'dd/mm' to be valid.";
    if (isNaN(day) || isNaN(month) && bdate !== "") throw "The date must contain numbers.";
    if (day > 31 && bdate !== "") throw "You seem to have done a typo with your birth day.";
    if (month > 12 && bdate !== "") throw "You seem to have done a typo with your birth month.";
}
catch(err) {
    alert(err);
    console.error(err);
}

// Valid email address
email = document.getElementById("email").value;
var searchAt = email.indexOf("@");
var searchDot = email.indexOf(".");
try{
    if (email == "") throw "You have not given your email.";
    if (searchAt == -1) throw "Your email must contain an '@' symbol.";
    if (searchDot == -1) throw "Your email must contain a . ";
}
catch(err){
    alert(err);
    console.error(err);
}

};

I would appreciate some help getting the function to go back to the form if validation fails. It works correctly for the name validation but not after the birthday validation. Thanks in advance.

Travis
  • 5
  • 2
  • You really should look into semantic markup for form validation. Most of what you are writing already exists and can be activated by form element attributes like `required`, birth date could just be a ` – Chase Jun 04 '20 at 02:13

2 Answers2

1

Try this:

onclick="validate(event)"

function validate(e){
e.preventDefault();
// Required first name
fname = document.getElementById("fname").value;
try{...

It shoul prevent your form going to action. Then you just need to deal with the redirects inside the function.

GM-atteoni
  • 425
  • 4
  • 11
  • Ok thank you the code above prevents the form action while validation fails however now it doesnt redirect when the validation passes. Is there a way to goto default if return is true? – Travis Jun 04 '20 at 02:33
  • Try reading this :) https://stackoverflow.com/questions/7610871/how-to-trigger-an-event-after-using-event-preventdefault It is not the best way but you can fix your problem. Hope it helps you. – GM-atteoni Jun 04 '20 at 02:42
0

change your input type to button as you have an onclick function like this below

HTML

<button id="submit" onclick="validate(event)">Submit</button>

JS

Added event.preventDefault()

function validate(event){
     event.preventDefault();
    // Required first name
    fname = document.getElementById("fname").value;
    try{
        if (fname == "") throw "You have not given your first name.";
    }
    catch(err) {
    alert(err);
    console.error(err);
    }

    // valid date format
    bdate = document.getElementById("bdate").value;
    var contains = bdate.indexOf("/");
    var day = bdate.slice(0, 2);
    var month = bdate.slice(3); 
    try{
        if (contains != 2 && bdate !== "") throw "The date must be in the following format 'dd/mm' to be valid.";
        if (isNaN(day) || isNaN(month) && bdate !== "") throw "The date must contain numbers.";
        if (day > 31 && bdate !== "") throw "You seem to have done a typo with your birth day.";
        if (month > 12 && bdate !== "") throw "You seem to have done a typo with your birth month.";
    }
    catch(err) {
        alert(err);
        console.error(err);
    }

    // Valid email address
    email = document.getElementById("email").value;
    var searchAt = email.indexOf("@");
    var searchDot = email.indexOf(".");
    try{
        if (email == "") throw "You have not given your email.";
        if (searchAt == -1) throw "Your email must contain an '@' symbol.";
        if (searchDot == -1) throw "Your email must contain a . ";
    }
    catch(err){
        alert(err);
        console.error(err);
    }

    };
Always Helping
  • 14,316
  • 4
  • 13
  • 29