DEV Community

Cover image for Creating Customized Offline Captcha in Angular 🔥✌
Hassan Farooqui
Hassan Farooqui

Posted on

Creating Customized Offline Captcha in Angular 🔥✌

Hola Folks!!

We are going to develop our offline captcha with typescript in just 5 minutes.

Only 5 steps we are going to follow:

  • create function for random string

  • initialize a variable array to store random string

  • Generate captcha of your desired length i.e. 4 or 5 and so on.

  • call that random string with a background image in template file

  • validate and refresh captcha

Let's start

Step 1

 makeRandom(lengthOfCode: number, possible: string)
{
    let text = "";
    for(let i = 0; i< lengthOfCode; i++)
    {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
    return text;
}
Enter fullscreen mode Exit fullscreen mode

above is the function for generating random string. now lets go further.

Step 2

Initializing variables as follows:

  captchaText: any =[]
  captchaEntered: String = ""

Enter fullscreen mode Exit fullscreen mode

now so variable has been initialized, lets call makeRandom function to generate desired captcha.

Step 3

generateCaptcha()
{
  let possible= "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
  const lengthOfCode = 1

  for (let i=0; i< 5; i++)
  {
    let captchaChar = this.makeRandom (lengthOfCode, possible)
    this.captchaText[i] = captchaChar
  }
}

Enter fullscreen mode Exit fullscreen mode

generateCaptcha function can be used on refresh button as well to regenerate captcha.

step 4
So now captcha has been generated, we are now calling it on our browser page.

<div style="background-image: url('./assets/captcha.jpg');">
  <div *ngFor="let captcha of captchaText">
    <b>{{captcha}}</b>
  </div>
</div>

<div>
  <input type="text" [(ngModel)]="this.captchaEntered" maxlength="5">
</div>
Enter fullscreen mode Exit fullscreen mode

you can use any image suitable to you as a captcha background.
secondly you can validate or refresh captcha on your desired submit button.

step 5
So the last one we are validating the captcha end user entered:


validateCaptcha ()
{
  let i=0
  this.captchaEntered = this.captchaEntered.toLocaleUpperCase()
  for (i; i<5; i++)
  {
    if (this.captchaEntered.charAt(i) != this.captchaText[i])
    {
      alert('wrong captcha entered')
      return
    }
  }

  //captcha verified your further code here

}

Enter fullscreen mode Exit fullscreen mode

_here you go enjoy!!!!! _

Top comments (0)