Text captcha implemntation using knockout custom binding.
npm install knockout-text-captchajavascript
import * as ko from 'knockout';
import { BindingHandler, ObservableArray } from 'knockout';
import Captcha from '../../external/jquery-captcha';
const captchaBinding = {
init: (elm: any, va: () => any, all: () => any, vm: any) => {
const cmp: any = va();
const cp = new Captcha(elm, cmp.captchaConfig);
cmp.isCaptchaValid = () => {
const isValid = cp.valid(cmp.captchaInput());
// Refresh captcha if its not valid
if (!isValid) {
cp.refresh();
cmp.captchaInput('');
}
return isValid;
}
cmp.refreshCaptcha = () => {
cp.refresh();
cmp.captchaInput('');
cmp.clearError();
}
}
}as BindingHandler;
export default captchaBinding;
`
Captcha component which uses captcha binding
`javascript
class CaptchaComponent {
captchaInput: Observable;
disableFields: Observable;
showSuccessMsg: Observable;
captchaConfig: any;
isCaptchaValid: (() => boolean) | undefined;
refreshCaptcha!: () => void;
constructor(params: any) {
this.disableFields = params.disable;
this.captchaConfig= params.config? params.config :{
width: 100,
height: 40,
font: 'bold 23px Arial',
resourceType: 'aA0@',
resourceExtra: [],
caseSensitive: true,
autoRefresh: false,
clickRefresh: false
};
this.showSuccessMsg = ko.observable(false);
this.captchaInput = ko.observable('').extend({
validation: {
validator: () => {
if (this.isCaptchaValid) {
const isValid=this.isCaptchaValid();
this.showSuccessMsg(isValid);
return isValid;
}
return false;
},
message: "Please Enter Valid Captcha",
}
});
}
refresh() {
if (this.refreshCaptcha) {
this.refreshCaptcha();
}
}
clearError(): void {
let errors = ko.validation.group(this);
errors.showAllMessages(false);
}
}
export default {
viewModel: CaptchaComponent,
template:
};
``