Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - jQuery validate only get triggered on the second submit

I have the jquery validation function in the javascript which will get called from react js function.

React JS

function handleFormSubmit(e){
    e.preventDefault()
    window.validateForm();
}

return (
    <form id="contactForm" onSubmit={handleFormSubmit} novalidate="novalidate">
        <input name="name" id="name" type="text" placeholder="Name" onChange={handleInputChange} />
        <textarea name="address" id="address" cols="4" rows="4" placeholder="Address" onChange={handleInputChange}></textarea>
        <button type="submit">Submit</button>
    </form>
)

JavaScript

function validateForm(){
    $("#contactForm").validate({
        rules: { 
            name: { required: true }, 
            address: { required: true }
        },
        messages: {
            name: { required: "Name field is required" },
            address: { required: "Address field is required" }
        }
    });
}

The first submit is calling the validateForm() function but it won't trigger the jquery validate(). It only get triggered on the second submit click.

question from:https://stackoverflow.com/questions/65885916/jquery-validate-only-get-triggered-on-the-second-submit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason is because you are assigning the Validation on the first click. It assigns its own event listener. The second click runs it and you also reassign the validate code again.

You need to just call the code on document ready. So get rid of the on submit

I have the jQuery validation function in the javascript which will get called from react js function.

$(function () {
  window.validateForm();
});

And seeing you are using jQuery with React, it is a bit more complicated than that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...