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;
}
above is the function for generating random string. now lets go further.
Step 2
Initializing variables as follows:
captchaText: any =[]
captchaEntered: String = ""
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
}
}
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>
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
}
_here you go enjoy!!!!! _
Top comments (0)