HTML/[removed] Simple form validation on submit

后端 未结 6 2162
北荒
北荒 2020-11-29 05:40

I\'m trying to validate my form with the easiest way possible, but somehow it is not working and when I click submit it just takes me to the next page without giving the ale

6条回答
  •  醉话见心
    2020-11-29 05:54

    Disclosure: I wrote FieldVal.

    Here is a solution using FieldVal. By using FieldVal UI to build a form and then FieldVal to validate the input, you can pass the error straight back into the form.

    You can even run the validation code on the backend (if you're using Node.js) and show the error in the form without wiring all of the fields up manually.

    Live demo: http://codepen.io/MarcusLongmuir/pen/WbOydx

    function validate_form(data) {
        // This would work on the back end too (if you're using Node)
    
        // Validate the provided data
        var validator = new FieldVal(data);
        validator.get("email", BasicVal.email(true));
        validator.get("title", BasicVal.string(true));
        validator.get("url", BasicVal.url(true));
        return validator.end();
    }
    
    
    $(document).ready(function(){
    
        // Create a form and add some fields
        var form = new FVForm()
        .add_field("email", new FVTextField("Email"))
        .add_field("title", new FVTextField("Title"))
        .add_field("url", new FVTextField("URL"))
        .on_submit(function(value){
    
            // Clear the existing errors
            form.clear_errors();
    
            // Use the function above to validate the input
            var error = validate_form(value);
    
            if (error) {
                // Pass the error into the form
                form.error(error);
            } else {
                // Use the data here
                alert(JSON.stringify(value));
            }
        })
    
        form.element.append(
            $("

提交回复
热议问题