Search code examples
ruby-on-railsclient-side-validation

rails client_side_validations only on hit save


I don't want the clien-side-validations validate on blur the inputs, just when I hit save.

Is this possible? How can I do this?

I have just some simple validations (empty, basically)... and I'm thinking about write it by hand.. does it worth?


Solution

  • You can easily do it with pure Javascript or with the help of any of JQuery/Prototype and similar frameworks.

    Here is a code that I tried with JQuery

    <html>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <body>
            <form id="my_form" action="http://google.com?q=ruby" method="GET">
                <input type="text" name="first_name" placeholder="First Name" /> <br/>
                <input type="text" name="last_name" placeholder="Last Name" /> <br/>
                <input type="text" name="city" placeholder="City" /> <br/>
                <input id="form_button" type="button" value="Submit"/>
            </form>
        </body>
    </html>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#form_button").on('click', function() {
                var form_valid = true;
                $("#my_form > input[type='text']").each(function() {
                    if(this.value == "") {
                        var error_span_present = $(this).next("span").length != 0;
                        if(!error_span_present) {
                            $("<span style='color:red;'>" + $(this).attr("placeholder") + " cannot be Blank </span>").insertAfter($(this));
                        } 
                        else { 
                            $(this).next("span").html($(this).attr("placeholder") + " cannot be Blank");
                        } 
                        form_valid = false;
                    }   
                    else {
                        if($(this).next("span").length != 0) {
                            $(this).next("span").remove();
                        } 
                    }
                });
                if(form_valid){ 
                    $("#my_form").submit();
                }
            });
        });
    </script>
    

    Here is the JSFiddle that demos this code.

    Hope this helps