Showing posts with label form validation. Show all posts
Showing posts with label form validation. Show all posts

Saturday, February 11, 2017

Pass old input/ get old input from view after Form Request validation in laravel

Sometimes we need to get old values in form to show them when error back to the same form, It is now well organized in Laravel. Consider the following situations:

1. Suppose you submitted a form with some values.
2. Found some errors and send back to the form again from Laravel controller to show the form again.
3. You have to show the values when he was here few moments ago (before submit the form)

$username = Request::old('username');

or in view:

{{ old('username') }}

Tuesday, December 13, 2016

Angularjs Focus Specific Error Input On Form Submit

<!doctype html>
<html>
<head>
    <title>Angularjs Focus Specific Error Input On Form Submit</title>
    <script src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>

<div data-ng-app="myApp" data-ng-controller="MyController">
    <form name="myForm" method="get" validate-form novalidate>
        <div class="container">
            Name: <input type="text" name="name" ng-model="name" ng-required="true" ng-maxlength="10" ng-minlength="5" my-validation/>
        </div>
        <div class="container">
            Email: <input type="email" name="email" ng-model="email" ng-required="true" my-validation/>
        </div>
        <div class="container">
            Type:
            <input type="radio" name="type" ng-model="type" value="A" ng-required="true" my-validation/> A
            <input type="radio" name="type" ng-model="type" value="B" ng-required="true" my-validation/> B
            <input type="radio" name="type" ng-model="type" value="C" ng-required="true" my-validation/> C
        </div>
        <div><input type="submit" value="Submit"/></div>
    </form>
</div>

<script type="text/javascript">
    var app = angular.module("myApp", []);

    app.controller("MyController", function($scope) {
        $scope.name = "";
        $scope.email = "";
    });

    app.directive('validateForm', function () {
        return {
            restrict: 'A',
            link: function ($scope, form) {
                form.on('submit', function () {
                    $(form).find(".container").css("border", "");
                    if($scope.myForm.$invalid) {
                        var error = $scope.myForm.$error;
                         for (var key in $scope.myForm.$error) {
                             for (var index = 0; index < $scope.myForm.$error[key].length; index++) {
                                 var err = $scope.myForm.$error[key][index];
                                 console.log("Field=" + err.$name + ', Error=' + key);
                             }
                         }


                        var firstInvalid = $(form[0].querySelector('.ng-invalid'));

                        if (firstInvalid.length > 0) {
                            firstInvalid.closest(".container").addClass("error_element").css("border", "2px solid red");
                            firstInvalid.focus();
                            return;
                        }
                    }
                    alert("Form Validated");
                });
            }
        };
    });

    app.directive("myValidation", function() {
        return {
            restrict: "A",
            require: "ngModel",
            link: function(scope, elem, attrs, ctrl) {
                console.log(attrs)
            }
        }
    })
</script>

</body>
</html>


Friday, November 25, 2016

How to add custom validation to an AngularJS form field


<!DOCTYPE html>
<html>
<head>
<title>How to add custom validation to an AngularJS form field</title>
<style type="text/css">
    div.log {
        border: 2px solid gray;
        color: black;
        padding: 10px;
        font-size: 20px;
        font-family: monospace;
    }
    div.log div {
        padding: 10px;
    }
</style>

<script src="http://code.angularjs.org/1.2.12/angular.js"></script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

<script type="text/javascript">
    var app = angular.module("myApp", []);

    app.controller("MyCustomValidationController", function($scope, $http) {
        $scope.items = [];
        $scope.items.push({"name": "Pritom", "type": "A"});
        $scope.items.push({"name": "Kumar", "type": "B"});

        var log = $(".log");
        $scope.log = function(e) {
            log.prepend("<div>" + e + "</div>");
        }

        $scope.error = function(e) {
            log.prepend("<div style='color:red;'>" + e + "</div>");
        }
    })

    app.directive("myCustomValidation", function() {
        return {
            restrict: "A",
            require: "ngModel",         
            link: function(scope, elem, attrs, ctrl) {
                ctrl.$parsers.unshift(function(v) {
                    scope.$evalAsync(function() {
                        scope.log("Parsers=" + v)
                    })
                    if(v.length > 10) {
                        ctrl.$setValidity('myCustomValidation', false)
                    }
                    else {
                        ctrl.$setValidity('myCustomValidation', true)
                    }
                    return v
                })
                ctrl.$formatters.unshift(function(v) {
                    scope.$evalAsync(function() {
                        scope.log("Formatters=" + v)
                    })
                    return v
                })
                elem.on('keyup', function (evt) {
                    if(ctrl.$error.maxlength) {
                        scope.$evalAsync(function() {
                            scope.error("Maxlength")
                        })
                    }
                    if(ctrl.$error.required) {
                        scope.$evalAsync(function() {
                            scope.error("Required")
                        })
                    }
                    if(ctrl.$error.myCustomValidation) {
                        scope.$evalAsync(function() {
                            scope.error("MyCustomValidation")
                        })
                    }
                })
            }
        }
    })
</script>
</head>

<body>
 <div data-ng-app="myApp" data-ng-controller="MyCustomValidationController">
     <div>
         <div ng-form="myForm" data-ng-repeat="item in items">
             <div style="border:1px solid blue;padding:10px;">
                <input type="text" name="name" ng-model="item.name" ng-maxlength="10" 
                       my-custom-validation required style="width:50%;"/>
                <select ng-model="item.type" my-custom-validation required style="width:48%;" name="type">
                    <option value="">None</option>
                    <option value="A">A</option>
                    <option value="B">B</option>
                    <option value="C">C</option>
                </select>
             </div>
         </div>
         <div class="log"></div>
     </div>
 </div>
</body>
</html>


Tuesday, February 18, 2014

Check the validity of an HTML5 form that does not contain a submit button


/* Check if html5 validation enabled */
function hasHtml5Validation () {
    return typeof document.createElement('input').checkValidity === 'function';
}


var $form = $("form");
$form.find("input.save-and-next").click(function() {
    $form.find(":input").each(function() {
        //if(!$(this).checkValidity()) {
        if(!$(this)[0].checkValidity()) {            
            $form.find("input[type='submit']").click();
            return false;
        }
    });
});

When you select  $(this) you get a collection of nodes, to access actual DOM properties you must select the numbered one such $(this)[0].

Or you can bind validation process to a form field such as:

form.find("input[type='text']").keyup(function() {
    if(!$(this)[0].checkValidity()) {
        form.find("input[type='submit']").click();
    }
});

Monday, January 13, 2014

Html5 & jQuery form validation and get all error at a time


Html code


<form method='post'>
    <ul class="errorMessages"></ul>
    <div class="one">
        <label for="name">Name:</label>
        <input id="name" type="text" required="required"/>
    </div>
    <div class="two">
        <label for="comments">Comments:</label>
        <textarea id="comments" required="required"></textarea>
    </div>
    <div class="three">
        <label for="roll">Name:</label>
        <input id="roll" type="text" required="required"/>
    </div>
    <div class="four">
        <label for="email">Email:</label>
        <input id="email" type="email" required="required"/>
    </div>
    <div class="five">
        <label>Group:</label>
        <input type='radio' name='group' required="required"/> Group 1
        <input type='radio' name='group' required="required"/> Group 2
        <input type='radio' name='group' required="required"/> Group 3
    </div>
    <div class="buttons">
        <button type="submit" class="submit">Submit</button>
        <button type="button">Check</button>
    </div>
</form>

jQuery code


var createAllErrors = function() {
    var form = $( this ), errorList = $( "ul.errorMessages", form);
    var showAllErrorMessages = function() {
        errorList.empty();
        
        // Find all invalid fields within the form.
        var invalidFields = form.find( ":invalid" ).each( function( index, node ) {
            // Find the field's corresponding label
            var label = $( "label[for=" + node.id + "] ").html();
            if(label === undefined) {
                label = "";
            }
            // Opera incorrectly does not fill the validationMessage property.
            var message = node.validationMessage || 'Invalid value.';
            errorList.append( "<li><span>" + label + "</span> " + message + "</li>" );
        });
        errorList.show();
        return errorList.find("li").size();
    };

    form.find("button[type='button']").click(function() {
        var errorLength = showAllErrorMessages();
        errorList.show().prepend( "<li><span>Total Errors: </span> " + errorLength + "</li>" );
        form.find( "button.submit").click();
    });
    
    // Support Safari
    form.on( "submit", function( event ) {
        if ( this.checkValidity && !this.checkValidity() ) {
            $( this ).find( ":invalid" ).first().focus();
            event.preventDefault();
        }
    });
};
$( "form" ).each( createAllErrors );