简体   繁体   中英

Custom form validation in AngularJS

I have created one custom directive to validate the "domain" name form field.

form field element as

<input type="text" autofocus name="domain" ng-model="user.domain" domain-validate="/^[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" >

custom directive code is

app.directive('domainValidate', function() {
    return {



    // element must have ng-model attribute.
    require: 'ngModel',

    // scope = the parent scope
    // elem = the element the directive is on
    // attr = a dictionary of attributes on the element
    // ctrl = the controller for ngModel.
    link: function(scope, elem, attr, ctrl) {

        //get the regex flags from the regex-validate-flags="" attribute (optional)
        var flags = attr.domainValidateFlags || 'i';

        // create the regex obj.
        var regex = new RegExp(attr.domainValidate, flags);

        // add a parser that will process each time the value is
        // parsed into the model when the user updates it.
        ctrl.$parsers.unshift(function(value) {
            // test and set the validity after update.
            var valid = regex.test(value);
            ctrl.$setValidity('domainValidate', valid);

            // if it's valid, return the value to the model,
            // otherwise return undefined.
            return valid ? value : undefined;
        });

        // add a formatter that will process each time the value
        // is updated on the DOM element.
        ctrl.$formatters.unshift(function(value) {
            // validate.
            console.log(value)
            ctrl.$setValidity('domainValidate', regex.test(value));

            // return the value or nothing will be written to the DOM.
            return value;
        });
    }
    };
});

I want to validate the field on form submit as well on value change.

The above code is not working, please can any one help me what is the error in above code or let me know how to validate the domain name field

thanks

oldish post and i'm noob at angular, but try this

        <form name="userForm" ng-submit="submit()" novalidate>

            <div>
                <input type="text" autofocus name="domain" ng-model="user.domain" domain-validate="^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$" required>
                <div ng-show="userForm.domain.$error.domainValidate">invalid domain</div>
                <div ng-show="userForm.domain.$dirty && userForm.domain.$error.required">required</div>
            </div>

            <button type="submit">Submit</button>

        </form>

then js directive

app.directive('domainValidate', function () {
return {

    require: 'ngModel',
    link: function (scope, elem, attr, ctrl) {

        //get the regex flags from the regex-validate-flags="" attribute (optional)
        var flags = attr.domainValidateFlags || 'i';

        // create the regex obj.
        var regex = new RegExp(attr.domainValidate, flags);

        function setValidity(value) {
            ctrl.$setValidity('domainValidate', regex.test(value));
        }

        scope.$watch(attr.ngModel, function (newValue, oldValue) {
            if (newValue !== undefined && newValue !== oldValue) {
                setValidity(newValue);
            }
        });

        scope.submit = function () {
            setValidity(ctrl.$modelValue);

            for (var error in ctrl.$error) {
                if (ctrl.$error[error]) return;
            }

            // send stuff
        }
    }
};
});

My suggestion is: Instead of custom directive validation use default URL validation:

<input type="url" autofocus name="domain" ng-model="user.domain">

Or if you don't want to use it, share your code in fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM