1

I'm trying to validate a form via javascript onSubmit, then run the php captcha verfication and email send action. The problem is that every time I try to check the fields, I can see just one of them highlited with my CSS classes (seems to be related to the 'return false;' which blocks me).

Anyone has a clue?

Here's my HTML form code (you can see it working here: https://jsfiddle.net/xfmsLa95/2/ ):

<form id="contact-form" class="contact" name="contact-form" method="POST" onsubmit="return checkInputs()" action="indexen.php">
                    <div class="fields">
                        <div class="field name">
                            <input type="text" name="name" id="name" placeholder="Name">
                            <i class="fas fa-check-circle"></i>
                            <i class="fas fa-exclamation-circle"></i>
                            <small>Error Message</small>
                        </div>
                        <div class="field email">
                            <input type="text" name="email" id="email" placeholder="Email">
                            <i class="fas fa-check-circle"></i>
                            <i class="fas fa-exclamation-circle"></i>
                            <small>Error Message</small>
                        </div>
                    </div>
                    <div class="field">
                        <input type="text" name="subject" id="subject" placeholder="Subject">
                        <i class="fas fa-check-circle"></i>
                        <i class="fas fa-exclamation-circle"></i>
                        <small>Error Message</small>
                    </div>
                    <div class="field textarea">
                        <textarea name="message" id="message" cols="30" rows="10" placeholder="Message..."></textarea>
                        <i class="fas fa-check-circle"></i>
                        <i class="fas fa-exclamation-circle"></i>
                        <small>Error Message</small>
                    </div>
                    <div class="button-area">
                    <button type="submit" name="submit">Submit</button>
                    </div>  
                </form>

And this is my validator.js file:

const username = document.getElementById('name');
const email = document.getElementById('email');
const subject = document.getElementById('subject');
const msg = document.getElementById('message');

function checkInputs() {

    const usernameValue = username.value.trim();
    const emailValue = email.value.trim();
    const subjectValue = subject.value.trim();
    const msgValue = msg.value.trim();

    if(usernameValue === '') {
        setErrorForUser(username, 'Name cannot be blank');
        return false;
    }
    else{
        setSuccessForUser(username);
    }

    if(emailValue === '') {
        setErrorForEmail(email, 'Email cannot be blank');
        return false;
    }

    else if(!isEmail(emailValue)){
        setErrorForEmail(email, 'Invalid email');
        return false;
    }

    else {
        setSuccessForEmail(email);
    }
    
    if(subjectValue === '') {
        setErrorForSubject(subject, 'Subject cannot be blank');
        return false;
    }

    else{
        setSuccessForSubject(subject);
    }

    if(msgValue === '') {
        setErrorForMsg(msg, 'Message cannot be blank');
        return false;
    }

    else{
        setSuccessForMsg(msg);
    }

    return true;

}

function setErrorForUser(input, message) {

    const formControl = input.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field error name';
}

function setSuccessForUser(input) {

    const formControl = input.parentElement;

    formControl.className = 'field name success';
}

function setErrorForEmail(input, message) {
    const formControl = input.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field email error';
}

function setSuccessForEmail(input) {

    const formControl = input.parentElement;

    formControl.className = 'field email success';
}

function setErrorForMsg(element, message) {

    const formControl = element.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field textarea error';
}

function setSuccessForMsg(element) {

    const formControl = element.parentElement;

    formControl.className = 'field textarea success';
}


function setErrorForSubject(input, message) {

    const formControl = input.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field error';
}

function setSuccessForSubject(input) {

    const formControl = input.parentElement;

    formControl.className = 'field success';
}

function isEmail(email) {
    return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}

PHP is working.

I'm adding some pictures to refer this. This is what I get:

error

But I want to get something like this:

example

To validate field per field like this:

validation

Thanks in advance,

3 Answers 3

1

As Advait_Nair said, you need to remove all return false in each conditions.

What I do in this case is setting a variable errors (array) where I add every field with an error. This way I know if there was errors and what field got one.

This way you can do something like :

function checkInputs() {

    const usernameValue = username.value.trim();
    const emailValue = email.value.trim();
    const subjectValue = subject.value.trim();
    const msgValue = msg.value.trim();
    var errors = []; // add errors array

    if(usernameValue === '') {
        setErrorForUser(username, 'Name cannot be blank');
        errors.push('username');
    }
    else{
        setSuccessForUser(username);
    }

    if(emailValue === '') {
        setErrorForEmail(email, 'Email cannot be blank');
        errors.push('email');
    }

    else if(!isEmail(emailValue)){
        setErrorForEmail(email, 'Invalid email');
        errors.push('email');
    }

    else {
        setSuccessForEmail(email);
    }
    
    if(subjectValue === '') {
        setErrorForSubject(subject, 'Subject cannot be blank');
        errors.push('subject');
    }

    else{
        setSuccessForSubject(subject);
    }

    if(msgValue === '') {
        setErrorForMsg(msg, 'Message cannot be blank');
        errors.push('message');
    }

    else{
        setSuccessForMsg(msg);
    }

    if (errors.length > 0) {
        // here you can display error message with fields list
        return false;
    }

    return true;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this in validator.js

const username = document.getElementById('name');
const email = document.getElementById('email');
const subject = document.getElementById('subject');
const msg = document.getElementById('message');

function checkInputs() {
    let isValid = true;
    const usernameValue = username.value.trim();
    const emailValue = email.value.trim();
    const subjectValue = subject.value.trim();
    const msgValue = msg.value.trim();

    if(usernameValue === '') {
        setErrorForUser(username, 'Name cannot be blank');
        isValid = false;
    }
    else{
        setSuccessForUser(username);
    }

    if(emailValue === '') {
        setErrorForEmail(email, 'Email cannot be blank');
        isValid = false;
    }

    else if(!isEmail(emailValue)){
        setErrorForEmail(email, 'Invalid email');
        isValid = false;
    }

    else {
        setSuccessForEmail(email);
    }
    
    if(subjectValue === '') {
        setErrorForSubject(subject, 'Subject cannot be blank');
        isValid = false;
    }

    else{
        setSuccessForSubject(subject);
    }

    if(msgValue === '') {
        setErrorForMsg(msg, 'Message cannot be blank');
        isValid = false;
    }

    else{
        setSuccessForMsg(msg);
    }

    return isValid;

}

function setErrorForUser(input, message) {

    const formControl = input.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field error name';
}

function setSuccessForUser(input) {

    const formControl = input.parentElement;

    formControl.className = 'field name success';
}

function setErrorForEmail(input, message) {
    const formControl = input.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field email error';
}

function setSuccessForEmail(input) {

    const formControl = input.parentElement;

    formControl.className = 'field email success';
}

function setErrorForMsg(element, message) {

    const formControl = element.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field textarea error';
}

function setSuccessForMsg(element) {

    const formControl = element.parentElement;

    formControl.className = 'field textarea success';
}


function setErrorForSubject(input, message) {

    const formControl = input.parentElement;
    
    const small = formControl.querySelector('small');

    small.innerText = message;

    formControl.className = 'field error';
}

function setSuccessForSubject(input) {

    const formControl = input.parentElement;

    formControl.className = 'field success';
}

function isEmail(email) {
    return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}

What I've done here is declared a variable called isValid and set it to true, and whenever the user puts something invalid in the filed it will change isValid to false, and at the very end of the function, it will return isValid.

Let's say you put a username to password wrong,

if(usernameValue === '') {
    setErrorForUser(username, 'Name cannot be blank');
    isValid = false;
}

the above code runs, and isValid is now false. and when the function is called, it will return isValid, which is false.

Now, let's say you put everything correctly, then isValid is never assigned false. Because isValid is by default true that means it will return true meaning everything is valid

1 Comment

Wonderful! Followed those steps and works like a charm. Thank you a lot!!!
0

You returned out of the function, which is why it only works for name, and not for anything else.

Basically, what happened was it found out that usernameValue was equal to nothing and so it ran setErrorForUser(username, 'Name cannot be blank'); and returned false.

When you call return in a function it will return something and will not run anything after that.

For example,

if we had the following code -

function doSomething() {
    console.log('Cake')
    return false;
    console.log('Zebra')
}

doSomething()

and we ran it, we would get 'Cake' but not 'Zebra' as we returned out of the function.

So try not returning false and see what happens

3 Comments

I see! Just tried it and I can see the 'error messages' showing up, but just right after that it runs the form action without any validation (even when it's populating blank spaces). I can't figure out how to run the form action only when it gets a success status.
@NahuelC Could you share the whole code? The snippet you've given of validator.js is just functions declared and not run.
This one should work: jsfiddle.net/xfmsLa95/2

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.