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
155 views
in Technique[技术] by (71.8m points)

javascript - AngularJS custom form validation using $http

I have a form that looks like this:

<form name="myForm" ng-submit="saveDeployment()">
    <input type="hidden" value="{{item.CloneUrl}}" name="cloneurl" />
    <input type="hidden" value="{{Username}}" name="username" />

    <input type="radio" name="deploymenttype" ng-model="item.deploymentType" value="azure" checked="checked">Azure 
    <br />
    <input type="radio" name="deploymenttype" ng-model="item.deploymentType" value="ftp">FTP

    <div id="azure" ng-show="item.deploymentType=='azure'">
        <label for="azurerepo">Azure Git Repo</label>
        <input type="text" name="azurerepo" ng-model="item.azurerepo" ng-class="{error: myForm.azurerepo.$invalid}" ng-required="item.deploymentType=='azure'" />
    </div>

    <div id="ftp" ng-show="item.deploymentType=='ftp'">
        <label for="ftpserver">FTP Server</label>
        <input type="text" name="ftpserver" ng-model="item.ftpserver" ng-class="{error: myForm.ftpserver.$invalid}" ng-required="item.deploymentType=='ftp'"  />

        <label for="ftppath">FTP Path</label>
        <input type="text" name="ftppath" ng-model="item.ftppath" ng-class="{error: myForm.ftppath.$invalid}" ng-required="item.deploymentType=='ftp'" />

        <label for="ftpusername">FTP Username</label>
        <input type="text" name="ftpusername" ng-model="item.ftpusername" ng-class="{error: myForm.ftpusername.$invalid}" ng-required="item.deploymentType=='ftp'"/>

        <label for="ftppassword">FTP Password</label>
        <input type="password" name="ftppassword" ng-model="item.ftppassword" ng-class="{error: myForm.ftppassword.$invalid}" ng-required="item.deploymentType=='ftp'"/>
    </div>

    <input type="submit" value="Save" ng-disabled="myForm.$invalid"/>

</form>

Its setup so that the required fields and Save button are all working once data is entered. However, part of my validation will be, "Is the user already registered?" where I will use the data entered to hit the server via POST using $http.

Should I put that logic in the saveDeployment() function or is there a better place to put it?

*UPDATE:*

I've implemented the below which is applied as an attribute on a element but it calls the server/database on every key press which I don't like:

 app.directive('repoAvailable', function ($http, $timeout) { // available
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ctrl) {
                console.log(ctrl);
                ctrl.$parsers.push(function (viewValue) {
                    // set it to true here, otherwise it will not 
                    // clear out when previous validators fail.
                    ctrl.$setValidity('repoAvailable', true);
                    if (ctrl.$valid) {
                        // set it to false here, because if we need to check 
                        // the validity of the email, it's invalid until the 
                        // AJAX responds.
                        ctrl.$setValidity('checkingRepo', false);

                        // now do your thing, chicken wing.
                        if (viewValue !== "" && typeof viewValue !== "undefined") {
                            $http.post('http://localhost:12008/alreadyregistered',viewValue) //set to 'Test.json' for it to return true.
                                .success(function (data, status, headers, config) {
                                    ctrl.$setValidity('repoAvailable', true);
                                    ctrl.$setValidity('checkingRepo', true);
                                })
                                .error(function (data, status, headers, config) {
                                    ctrl.$setValidity('repoAvailable', false);
                                    ctrl.$setValidity('checkingRepo', true);
                                });
                        } else {
                            ctrl.$setValidity('repoAvailable', false);
                            ctrl.$setValidity('checkingRepo', true);
                        }
                    }
                    return viewValue;
                });

            }
        };
    });
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You don't need to make $http request in directive, better place for it is controller.

You can specify method inside controller - $scope.saveDeployment = function () { // here you make and handle your error on request ... }; you'll save error to scope and then create a directive that will watch $scope.yourResponseObject and set validity based on it.

Also if you need something like request and error on input field blur instead, you need to create a simple directive with elem.bind('blur', ...) where you call $scope.saveDeployment with callback to handle validity.

Take a look on the examples, there might be something similar - https://github.com/angular/angular.js/wiki/JsFiddle-Examples


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

...