Libetia A

Libetia A

1572943562

How to Validation and Controls Password in Angular

In this post, we are going to be creating a simple signup form, with email, password and confirm password controls. We will then validate the data to ensure it fulfills our requirement before a user can submit the form. We are going to enforce the following rules for the password:

  • Must be at least 8 characters in length,
  • Must be alphanumeric, with at least one upper and one lower case character
  • And must have at least one special character.

We are going to validate each of the 5 rules individually using RegExp. And then, we will display a nice visual interface indicating to the user which rule they have not fulfilled. We will also be checking to see whether the password and the confirmation passwords are a match. Here is what the end-product will look like:

This is image title

Getting Started

First, we are going to create a new project using Angular CLI.

$ ng new ng-bootstrap-password-validation-example

Then, we need to install and setup bootstrap for our angular project. First, install bootstrap using your favorite package manager:

$ npm install -s bootstrap

// or

$ yarn add bootstrap

Then, add  bootstrap SCSS Styles to the list of styles for your project inside your angular.json file. There are three of them, but only one is necessary - node_modules/bootstrap/scss/bootstrap.scss.

"styles": [
  "src/styles.css",
  "node_modules/bootstrap/scss/bootstrap-grid.scss",
  "node_modules/bootstrap/scss/bootstrap-reboot.scss",
  "node_modules/bootstrap/scss/bootstrap.scss"
],

Next, we need to add material icons to our angular project. Open your index.html (Located inside the src directory at the root of your angular workspace) and add the following link:

<link
  href="https://fonts.googleapis.com/icon?family=Material+Icons"
  rel="stylesheet"
/>

This is the easiest way to add material icons to your project. If you are interested in learning of the other ways of adding material icons to any project, you can visit the official guide here. And finally, we need to vertically re-align material icons, so they appear more centralized. We will use the following CSS code:

.material-icons {
   display: inline-flex;
   vertical-align: middle;
}

Add the above code in your app styles, by default its styles.css located under the src directory at the root of your angular workspace. The last thing we need to do is import the modules we need in our app module. In this project, we are going to require ReactiveFormsModule only, since we are building a reactive form. So, let’s add that module to our imports in the app module (By default app.module.ts).

@NgModule({
  ...
  imports: [
   BrowserModule,
   ReactiveFormsModule
  ],
  ...
})
export class AppModule {}

Building a Custom Validator

Angular provides built in validators, but in our case they won’t help us achieve what we want. We need a custom validator that uses regex to check whether a password contains a special character or a number and report the error to back to us.

NB: If you want to learn more about creating a custom validator, please visit the following link where I cover it in greater details.

So, our custom validator will accept the validation RegExp expression, and validation error object to return if it encounters an error. For instance, if we want to check whether it has a number, we will pass the following:

patternValidator(/\d/, { hasNumber: true }),

Where /\d/ is the RegExp expression for checking if it has a number and { hasNumber: true } is our error to return. The error part of our parameters will allow us to use the control.hasError("hasNumber") within our template, when checking whether to show the error. Now, let’s build our validator. First, we are going to create a CustomValidators class, where we can place multiple custom validator methods for our project.

$ ng g class custom-validators

Then, we are going to add a static pattern validator (patternValidator) method.

NB: Follow the comments to see what individual lines of code do.

static patternValidator(regex: RegExp, error: ValidationErrors): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    if (!control.value) {
      // if control is empty return no error
      return null;
    }

    // test the value of the control against the regexp supplied
    const valid = regex.test(control.value);

    // if true, return no error (no error), else return error passed in the second parameter
    return valid ? null : error;
  };
}

And we also need a second CustomValidator to check whether our password and confirm password are a match. Add a second customValidator, called passwordMatchValidator and add the following code.

NB: You can follow the comments on the code for what individual lines do.

static passwordMatchValidator(control: AbstractControl) {
  const password: string = control.get('password').value; // get password from our password form control
  const confirmPassword: string = control.get('confirmPassword').value; // get password from our confirmPassword form control
  // compare is the password math
  if (password !== confirmPassword) {
    // if they don't match, set an error in our confirmPassword form control
    control.get('confirmPassword').setErrors({ NoPassswordMatch: true });
  }
}

Building Our Signup Form

For this project, we are going to use the default component – AppComponent.

Component Class

First, we need to inject the FormBuilder in to our component.

constructor(private fb: FormBuilder) {}

Next, we need to add a new property in our component class – frmSignup, that will hold information about our form:

public frmSignup: FormGroup;

Next, we need to create a method for adding form controls to the frmSignup property we just created above: We call the method createSignupForm, and it will return a FormGroup class.

createSignupForm(): FormGroup {}

Then inside the createSignupForm() method above, we need to add the controls for our form and the validation rules required.

NB: Follow the comments below for more information about individual lines of code.

createSignupForm(): FormGroup {
  return this.fb.group(
    {
      // email is required and must be a valid email email
      email: [null, Validators.compose([
         Validators.email,
         Validators.required])
      ],
      password: [ null, Validators.compose([
         // 1\. Password Field is Required
         Validators.required,
         // 2\. check whether the entered password has a number
         CustomValidators.patternValidator(/\d/, { hasNumber: true }),
         // 3\. check whether the entered password has upper case letter
         CustomValidators.patternValidator(/[A-Z]/, { hasCapitalCase: true }),
         // 4\. check whether the entered password has a lower-case letter
         CustomValidators.patternValidator(/[a-z]/, { hasSmallCase: true }),
         // 5\. check whether the entered password has a special character
         CustomValidators.patternValidator(/[ [!@#$%^&*()_+-=[]{};':"|,.<>/?]/](<mailto:!@#$%^&*()_+-=[]{};':"|,.<>/?]/>), { hasSpecialCharacters: true }),
         // 6\. Has a minimum length of 8 characters
         Validators.minLength(8)])
      ],
      confirmPassword: [null, Validators.compose([Validators.required])]
   },
   {
      // check whether our password and confirm password match
      validator: CustomValidators.passwordMatchValidator
   });
}

Are you still with me? Now let’s move to our component template.

Component Template:

We will create a normal reactive form as you normally would:

<form [formGroup]="frmSignup" (submit)="submit()"></form>

Then, we add our individual form controls:

<input id="email" formControlName="email" type="email" class="form-control" />

Then, we need to show validation errors to users. For instance, to check whether the email provided is valid, we use the following expression:

frmSignup.controls['email'].hasError('email')

And the same for a required form field:

frmSignup.controls['email'].hasError('required')

And to display a message, we can simply use *ngIf:

<label
  class="text-danger"
  *ngIf="frmSignup.controls['email'].hasError('email')"
>
  Enter a valid email address!
</label>

NB: This will display the Enter a valid Email Address! error only when there is such an error. You can do the same for required, and custom validation errors.

The same goes for confirming whether confirm password and password are a match:

<label
  class="text-danger"
  *ngIf="frmSignup.controls['confirmPassword'].hasError('NoPassswordMatch')"
>
  Password do not match
</label>

We can also add a red border around our form field to give the error some prominence. We are going to add is-invalid bootstrap class using ngClass, adding the class when the form control has an error and remove it when there is no error:

[ngClass]="frmSignup.controls['email'].invalid ? 'is-invalid' : ''"

So, now our form field looks like this:

<input
  id="email"
  formControlName="email"
  type="email"
  class="form-control"
  [ngClass]="frmSignup.controls['email'].invalid ? 'is-invalid' : ''"
/>

Password Rules Validation

There is not much difference from the above code when it customs to custom validation rules.

<label
  class="text-danger"
  *ngIf="frmSignup.controls['password'].hasError('hasNumber')"
>
  Must have at least 1 number!
</label>

But, since we don’t want to just hide and show the errors as with other form fields, we want to show text with green font for rules the password has fulfilled, and a red font color for rules not fulfilled. So, instead of *ngIf, we will use a ngClass, to switch between bootstrap classes  text-success and text-danger.

[ngClass]="frmSignup.controls['password'].hasError('required') ||
frmSignup.controls['password'].hasError('hasNumber')  ? 'text-danger' :
'text-success'"

We also need to do the same for icons, showing a check icon when a rule has been fulfilled and cancel icon otherwise.

<i class="material-icons">
  {{ frmSignup.controls['password'].hasError('required') ||
  frmSignup.controls['password'].hasError('hasNumber') ? 'cancel' :
  'check_circle' }}
</i>

So, our complete code will look like this for checking whether password has a number:

<label
  class="col"
  [ngClass]="frmSignup.controls['password'].hasError('required') || frmSignup.controls['password'].hasError('hasNumber')  ? 'text-danger' :'text-success'"
>
  <i class="material-icons">
    {{
    frmSignup.controls['password'].hasError('frmSignup.controls['password'].hasError('hasNumber')
    ? 'cancel' : 'check_circle' }}
  </i>
  Must contain atleast 1 number!
</label>

And the same goes for our other password rules:

<label
  [ngClass]="frmSignup.controls['password'].hasError('required') || frmSignup.controls['password'].hasError('minlength')  ? 'text-danger' : 'text-success'"
>
  <i class="material-icons">
    {{ frmSignup.controls['password'].hasError('required') ||
    frmSignup.controls['password'].hasError('minlength') ? 'cancel' :
    'check_circle' }}
  </i>
  Must be at least 8 characters!
</label>

<label
  class="col"
  [ngClass]="frmSignup.controls['password'].hasError('required') || frmSignup.controls['password'].hasError('hasNumber')  ? 'text-danger' : 'text-success'"
>
  <i class="material-icons">
    {{ frmSignup.controls['password'].hasError('required') ||
    frmSignup.controls['password'].hasError('hasNumber') ? 'cancel' :
    'check_circle' }}
  </i>
  Must contain at least 1 number!
</label>

<label
  class="col"
  [ngClass]="frmSignup.controls['password'].hasError('required') || frmSignup.controls['password'].hasError('hasCapitalCase')  ? 'text-danger' : 'text-success'"
>
  <i class="material-icons">
    {{ frmSignup.controls['password'].hasError('required') ||
    frmSignup.controls['password'].hasError('hasCapitalCase') ? 'cancel' :
    'check_circle' }}
  </i>
  Must contain at least 1 in Capital Case!
</label>

<label
  class="col"
  [ngClass]="frmSignup.controls['password'].hasError('required') || frmSignup.controls['password'].hasError('hasSmallCase')  ? 'text-danger' : 'text-success'"
>
  <i class="material-icons">
    {{ frmSignup.controls['password'].hasError('required') ||
    frmSignup.controls['password'].hasError('hasSmallCase') ? 'cancel' :
    'check_circle' }}
  </i>
  Must contain at least 1 Letter in Small Case!
</label>

<label
  class="col"
  [ngClass]="frmSignup.controls['password'].hasError('required') || frmSignup.controls['password'].hasError('hasSpecialCharacters') ? 'text-danger' : 'text-success'"
>
  <i class="material-icons">
    {{ frmSignup.controls['password'].hasError('required') ||
    frmSignup.controls['password'].hasError('hasSpecialCharacters') ? 'cancel' :
    'check_circle' }}
  </i>
  Must contain at least 1 Special Character!
</label>

Demo and Source Code

You can find a demo to play with here and the complete source code for the above project here.

Thank you ! Happy coding !

#Angular #Typescript #security code #webdev

What is GEEK

Buddha Community

How to Validation and Controls Password in Angular

How To Validate Password And Confirm Password Using JQuery

In this post I will show you how to validate password and confirm password using jQuery, Validation is basic and important feature for authentication user so here i will give you demo about password and confirm password validation using jquery.

In jquery we are using keyup event to check whether password and confirm password is match or not.

Read More : How To Validate Password And Confirm Password Using JQuery

https://websolutionstuff.com/post/how-to-validate-password-and-confirm-password-using-jquery

#javascript #jquery #validation #validate password and confirm password #validate password in jquery #validate password and confirm password in jquery

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

How To Check Password Strength Using JQuery

In this post I will show you how to check password strength using jQuery, here I will check whether password strength is fulfill min character requirement or not.

I will give you example how to check password size using javascript and jQuery password strength. password is most important part of authentication many times you can see error message like enter valid password or password must be at least 6 character etc. So, here we are check password using jquery.

How To Check Password Strength Using JQuery

https://websolutionstuff.com/post/how-to-check-password-strength-using-jquery

#jquery #how to check password strength using jquery #validation #how to check password size using javascript #jquery password strength #jquery password validation

Angular Form Validation

In the last post I introduced angular 2’s model driven form approach. In this post I’m going to go through how to implement validation rules on a model driven form …

Standard validators

At the moment there seem to be 3 standard validators which pretty much do what they say on the tin:

  • Validators.required
  • Validators.minLength
  • Validators.maxLength

Here’s some component code that references the standard required and minLength validators:

export class LoginComponent {
  loginForm: ControlGroup;
  constructor(builder: FormBuilder) {
    this.loginForm = builder.group({
      userName: ["", Validators.required],
      password: ["", Validators.minLength(6)]
    });
  }
}

Multiple validators

You can use Validators.compose to specify multiple validators for a field:

export class LoginComponent {
  loginForm: ControlGroup;
  constructor(builder: FormBuilder) {
    this.loginForm = builder.group({
      userName: ["", Validators.required],
      password: [
        "",
        Validators.compose([Validators.minLength(6), Validators.maxLength(12)])
      ]
    });
  }
}

#angular #standard validators #multiple validators #custom validation