Recently, I wanted to add a captcha feature to my Django blog, which I wanted to do with a third-party library, but consider the impact of adding third-party libraries on performance and whether third-party libraries are safe and secure, or use your own code. Anyway, using JS to implement the verification code function is not very difficult.
Simply put, a create_code () method is used to generate the verification code in the page, and then the Control_submit () method detects the keyboard input event of the Captcha text box (id= "User_input_code"), and when the text box has entered more than 4 characters, Call Verify_code () to detect whether the input character matches the generated verification code.
If consistent, the disabled property of the Submit Comment button is changed from True to false, and if inconsistent, the verification code error is displayed on the page.
The JS code is as follows:
varCode;functionCreate_code () {//Generate verification CodeCode = ""; varCodelength = 4; varCheckcode = $ ("#checkCode"); varSelectchar =NewArray (0,1,2,3,4,5,6,7,8,9, ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L '), ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '); for(vari=0;i<codelength;i++){ varCharIndex = Math.floor (Math.random () *36); Code+=Selectchar[charindex]; } if(Checkcode) {Checkcode.addclass ("Code"); Checkcode.val (code); }}functionVerify_code () {//Verify the verification code varUser_input_code = $ ("#user_input_code"). Val (). toLowerCase (). Trim (); if(User_input_code.length <=0){ return false; } Else if(User_input_code! =code.tolowercase ()) { return false; } return true;}functionControl_submit () {//allow comments to be submitted when verification code verification is successful$ ("#user_input_code"). KeyUp (function () { if($ ("#user_input_code"). Val (). Trim (). length>=4) { if(Verify_code ()) {$ ("#submit_comment"). attr ("Disabled",false); } Else { $("#valid_failed"). Text ("Captcha error"); } } Else { $("#valid_failed"). Text (""); } });}
Add the following element to the corresponding form in the HTML page:
<form...> <inputID= "User_input_code"type= "text"name= "Code"placeholder= "Please enter the verification code on the right."/> <inputtype= "text"ReadOnly= "ReadOnly"ID= "Checkcode"class= "Code"style= "width:60px;" /> <PID= "Valid_faild"></P> <TR> <TDcolspan= "2"> <inputID= "Submit_comment"type= "Submit"Disabled= "true"name= "Submit"value= "Submit Comment"> </TD> </TR></form>
Finally in the CSS file to modify the verification code elements of the attributes, such as character spacing, color, background image, etc., you can complete the verification code function.