How can I simplify form validation?

前端 未结 11 1505
[愿得一人]
[愿得一人] 2020-12-14 00:57

The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty

11条回答
  •  别那么骄傲
    2020-12-14 01:45

    Check out my angularJS form validaton on codpen link

    I have showed an example how to validate required, minlength, maxlength, email, password case, confirm password match on my demo.

    Here is the code:

    var myApp = angular.module('myApp',[]);
    myApp.controller('mainController',['$scope', function($scope) {
    	
    }]);
    myApp.directive('validConfirmPassword', function() {
    	return {
    		require:'ngModel',
    		link: function(scope, elem, attrs, ctrl) {
    			ctrl.$parsers.unshift(function(viewValue, $scope) {
    				var noMatch = viewValue != scope.myForm.password.$viewValue;
    				ctrl.$setValidity('noMatch', !noMatch)
    			})
    		}
    	}
    })	
    .content{ margin-top:50px;  }
    .danger-text { color: red; }
    
    
    
    

    Please enter your first name

    Please enter your last name

    Please enter username

    Username is too short

    Username is too long

    Enter a valid email address

    Password is required

    Passwords must be between 8 and 20 characters.

    Must contain one lower & uppercase letter, and one non-alpha character (a number or a symbol.)

    Please confirm your password.

    Passwords do not match.

提交回复
热议问题