Angular JS form validation

Keywords: Attribute angular Javascript

Angular JS official website

Angular JS Basic Instructions

ng-model instruction

  • ng-model: Binding HTML controller values to application data
  • The ng-model instruction is used to bind application data to the value of the HTML controller (input,select,textarea)
  • ng-model specifies that the values of input fields can also be bound to variables created by Angular JS
<input ng-model="name">
{{name}}
  • Bidirectional binding: When changing the value of the input field, the value of the Angular JS property will also be changed
  • Application state: ng-model instructions can provide state values (invalid,dirty,touched,error) for application data.
    • ng-invalid: Unverified forms
    • ng-valid: Boolean property that indicates whether the form has passed validation. If the form is currently validated, it will be true
    • ng-dirty: Boolean value attribute that indicates whether the user has modified the form. If true, it means that the form has been modified; false means that it has not been modified.
    • ng-touched: Boolean property indicating whether a user has interacted with a control
    • ng-pristine: Boolean value attribute that indicates whether the user has modified the form. If true, it means no modification; false means modified.

ng-minlength and ng-maxlength instructions

<input type="text" ng-model="name" ng-minlength="3" ng-maxlength="10">
{{name}}

If the value of the input box is illegal, then {{name}} has no data binding and will not be displayed.
Note: When type="number", the value of the input box must be a number, otherwise it is illegal.

ng-submit and ng-class instructions

  • ng-submit: An expression that specifies the execution of onsubmit events when they occur
  • The ng-submit directive is used to execute the specified function after the form is submitted.
    <form name="signUpForm" ng-submit="submitForm()"></form>
  • ng-class: A CSS class that specifies the use of HTML elements
  • The ng-class directive is used to dynamically bind one or more CSS classes to HTML elements
  • The value of an ng-class instruction can be a string, an object, or an array.
    • If it is a string, multiple class names are separated by spaces.
    • If it is an object, you need to use the key-value pair, which is a Boolean value for the class name you want to add. Classes are added only when value is true.
    • If it is an array, it can be composed of strings or objects, and the elements of the array can be strings or objects.
      <input name="username" ng-model="username" ng-class="{'error':signUpForm.username.$invalid}" class="form-control" required>

ng-if directive

  • ng-if: If false removes HTML elements
  • The ng-if instruction is used to remove HTML elements when the expression is false.
    If the result of if statement execution is true, remove elements are added and displayed.
    The ng-if instruction is different from ng-hide, which hides elements, and ng-if removes elements from DOM.
    <div ng-if= "signUpForm. username. $invalid & signUpForm. username. $touched"> Your input is incorrect </div>

ng-disabled instruction

  • ng-disabled: specifies whether an element is disabled
  • The ng-disabled instruction sets the disabled attribute (input,select, or textarea) of the form input field.
    If the ng-disabled expression returns true, the form field will be disabled.
    <button type= "submit" ng-disabled= "signUpForm. $invalid"> submit </button>

Examples of form validation

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="lib/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="lib/font-awesome-4.7.0/css/font-awesome.css"/>
    <link rel="stylesheet" href="css/css.css" />
</head>
<body ng-app="myApp" ng-controller="SignUpController"> 
    <div class="wrapper">
        <h2>register</h2>
        <form name="signUpForm" ng-submit="submitForm()" novalidate ng-cloak>
            <div class="form-group" ng-class="{'has-success':signUpForm.username.$valid}">
                <label>User name:</label>
                <pre>legitimate:{{signUpForm.username.$valid}}</pre><!--The value is:true perhaps false-->
                <pre>username:{{userdata.username}}</pre><!--Input Value Legitimacy,Will be introduced-->
                <input name="username" 
                    type="text" 
                    class="form-control"
                    required
                    ng-model="userdata.username"
                    ng-minlength="4"
                    ng-maxlength="32"
                    >
                <div class="fa fa-check input_result success"
                    ng-if="signUpForm.username.$valid"></div>
                <p class="error"
                    ng-if="signUpForm.username.$error.required &&
                     signUpForm.username.$touched">
                     //User name cannot be empty
                </p>
                <p class="error"
                    ng-if="(signUpForm.username.$error.minlength ||
                     signUpForm.username.$error.maxlength) &&
                     signUpForm.username.$touched">
                     //User names should be between 4 and 32 bits long
                </p>
            </div>
            <div class="form-group"  ng-class="{'has-success':signUpForm.password.$valid}">
                <label>Password:</label>
                <pre>legitimate:{{signUpForm.password.$valid}}</pre>
                <pre>password:{{userdata.password}}</pre>
                <input name="password" 
                    type="password" 
                    class="form-control"
                    required
                    ng-model="userdata.password"
                    ng-minlength="6"
                    ng-maxlength="16"
                    >
                <div class="fa fa-check input_result success"
                    ng-if="signUpForm.password.$valid"></div>
                <p class="error"
                    ng-if="signUpForm.password.$error.required &&
                     signUpForm.password.$touched">
                    //Password cannot be empty
                </p>
                <p class="error"
                    ng-if="(signUpForm.password.$error.minlength ||
                     signUpForm.password.$error.maxlength) &&
                     signUpForm.password.$touched">
                     //Password length should be between 6 and 16 bits
                </p>
            </div>
            <div class="form-group"  ng-class="{'has-success':signUpForm.password2.$valid}">
                <label>Confirm password:</label>
                <pre>legitimate:{{signUpForm.password2.$valid}}</pre>
                <pre>password:{{userdata.password2}}</pre>
                <input name="password2" 
                    type="password" 
                    class="form-control"
                    required
                    ng-model="userdata.password2"
                    compare="userdata.password"
                    >
                <div class="fa fa-check input_result success"
                    ng-if="signUpForm.password2.$valid"></div>
                <p class="error" 
                    ng-if="(signUpForm.password2.$error.compare &&
                    signUpForm.password2.$touched)">
                    //Two inconsistent password input
                </p>
            </div>
            <div class="form-group">
                <button class="btn btn-primary">register</button>
            </div>
        </form>
    </div>
    <script type="text/javascript" src="lib/angular.js" ></script>
    <script type="text/javascript" src="js/js.js" ></script>
</body>
</html>

js.js

angular.module('myApp',[])
    .controller('SignUpController',function($scope){
        $scope.userdata={};
        $scope.submitForm=function(){
            console.log($scope.userdata);
            if($scope.signUpForm.$invalid){
                alert("Please check your information.");
            }else{
                alert("Submit successfully!");
            }
        }
    })
    .directive('compare',function(){//The definition instruction compare is consistent with the page compare attribute
        var o = {};
        o.strict = 'AE';//Define matching patterns as attributes and elements
        o.scope = {
            orgText:'=compare'//= Implementing binding of orgText to the value of the front compare attribute
        }
        o.require = 'ngModel';//Injecting the controller into the'ng-Model'instruction will find ng-Model on that element
        o.link = function(sco,ele,att,con){
            con.$validators.compare = function(v){//Add a compare method to the validator (the comparison in this place is not related to the instruction comparison foreground attribute comparison, but only a method name of the validator, related to the foreground $error. comparison)
                return v == sco.orgText;//Comparing the input parameter of the element (the tag ng-model binding value) with the value of orgText (comparison attribute value) returns true or false
            }
            sco.$watch('orgText',function(){//Monitor (run this method if the orgText value changes)
                con.$validate();//Call validation of the label
            })
        }
        return o;
    })

css.css

.red{
    background:#a30;
}
.error{
    color: #a10;
}
input.error{
    border:1px solid #a10;
}
.wrapper{
    width:200px;
    margin:30px auto;
}
.input_result{
    position: relative;
    top: -28px;
    left: 205px;
}
p.success{
    color: #3C763D;
}
pre{
    display: none;
}

Source download

Posted by ayok on Mon, 27 May 2019 13:27:43 -0700