0

I have a simple working ajax contact form (for the most part lol) and I have php validation that works and sends my email. My problem is the jquery portion, I want to validate and have error messages show based upon the kind of input error. Right now it seems like it always returns true for my first if statement (always says that there is no value in the input field). Where did my code go wrong?

if (!$.trim(("#contact-name").value).length) {
        console.log("Error: Required Name");
        $("#contact-name").next().text('Your name is required.');
}
    else { 
        var re = /^[a-zA-Z ]+$/;
        var is_name = re.test("#contact-name").val();
        if (is_name){
            error_free = true; 
            console.log("Success: Name is Valid");       
        }
        else {
            $("#contact-name").next().text('Your name cannot contain special characters');
            error_free = false;
            console.log("Error: Name cannot contain special characters");
        }
    }

1 Answer 1

2

for the first if statement, it should be:

if (!$.trim($("#contact-name").val()).length)

however, you might as well just do this

if(!$("#contact-name").val().trim())

which seems a little cleaner

Sign up to request clarification or add additional context in comments.

1 Comment

are you sure $("#contact-name").value is still correct? it should be $("#contact-name").val()

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.