controller connect to directive for validation

后端 未结 1 1930
野趣味
野趣味 2021-01-25 23:36

Hi I was wondering how I can combine both a directive and controller function for validating a form?

Right now I\'m validating a form separately with a directive, which

相关标签:
1条回答
  • 2021-01-26 00:09

    Though this does not directly answer your question, it is an alternative approach that might benefit you. First create a service to hold your validations.

    myApp.factory('ValidationService', [ '$log',
    function($log) {
    
    var validators = {
        passcode: {
            patterns: [
                {
                    regex: /^[0-9]{8}$/,
                    msg: "Please enter a valid 8 digit code."
                }
            ]   
        },
        password: {
            patterns: [
                {
                    regex: /^.{8}.*$/,
                    msg: "Please use at least 8 characters."
                },
                {
                    regex: /((?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[0-9].*))|((?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[^a-zA-Z0-9].*))|((?=.*[A-Z].*)(?=.*[0-9].*)(?=.*[^a-zA-Z0-9].*))|((?=.*[a-z].*)(?=.*[0-9].*)(?=.*[^a-zA-Z0-9].*))/,
                    msg: "Please use characters from 3 different categories."
                }
            ]
        },
        email: {
            patterns: [
                {
                    regex: /^[^@]+@[^.]+[.][^.][^.]+.*$/,
                    msg: "Please enter a valid email address."
                }
            ]
        },
        default: {
            patterns: [
                {
                    regex: /^.*$/,
                    msg: "Invalid validator specified. Check your html."
                }
            ]
        }
    };
    
    return {
        getValidator: getValidator
    };
    
    function getValidator(inputType) {
        if (validators[inputType]) {
            return validators[inputType];
        }
        return validators.default;
    }
    
    }]);
    

    Then, a directive to work with this service:

    myApp.directive('inputValidator', [ '$log', 'ValidationService',
    function($log, ValidationService) {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
    
            ctrl.$parsers.unshift(function(viewValue) {
                if (typeof viewValue == 'undefined') {
                    return viewValue;
                }
                var pass = true;
                var validator = ValidationService.getValidator(attrs.inputValidator);
                $.each(validator.patterns, function(index, pattern) {
                    if (!pattern.regex.test(viewValue)) {
                        pass = false;
                        scope[attrs.inputValidatorMsg] = pattern.msg;
                        return false;
                    }
                });
    
                if (pass) {
                    // valid
                    ctrl.$setValidity('inputValidator', true);
                    return viewValue;
                } else {
                    // invalid
                    ctrl.$setValidity('inputValidator', false);
                    return undefined;
                }
            });
        }
    };
    }]);
    

    And finally, some html to tie it all together:

    <form name="loginForm" class="css-form" data-novalidate>
                <p class="reset-header">Activate Your Account</p>
    
                <input type=text placeholder="Email Address" name="username" data-ng-model="username"
                        data-input-validator="email" data-input-validator-msg="usernameError" data-required>
                <span class="tag tag-alert arrow-top" data-ng-show="loginForm.username.$error.inputValidator">{{usernameError}}</span>
    
                <input type=text placeholder="Activation Code" name="passcode" data-ng-model="passcode"
                        data-input-validator="passcode" data-input-validator-msg="passcodeError" data-required>
                <span class="tag tag-alert arrow-top" data-ng-show="loginForm.passcode.$error.inputValidator">{{passcodeError}}</span>
    
                <input type=password placeholder="New Password" name="password" data-ng-model="password"
                        data-input-validator="password" data-input-validator-msg="passwordError" data-input-must-not-match="username" data-required>
                <span class="tag tag-alert arrow-top" data-ng-show="loginForm.password.$error.inputValidator">{{passwordError}}</span>
                <span class="tag tag-alert arrow-top" data-ng-show="!loginForm.password.$error.inputValidator && loginForm.password.$error.inputMustNotMatch">Please enter a password that is not your email address.</span>
    
                <input type=password placeholder="New Password Again" name="passwordConfirm" data-ng-model="passwordConfirm"
                        data-input-must-match="password" data-required>
                <span class="tag tag-alert arrow-top" data-ng-show="loginForm.passwordConfirm.$error.inputMustMatch">Please enter the same new password again.</span>
    
                <button class="btn btn-special" data-ng-disabled="loginForm.$invalid" data-ng-click="save()">Activate</button>
            </form>
    
    0 讨论(0)
提交回复
热议问题