简体   繁体   中英

Simple jquery input name form validation

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");
        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM