About .NET, ASP.NET, MVC, C#, WPF, WCF and everything related to .NET and more.

Captcha Mvc [ Getting started]

To start working with Captcha Mvc you should:

  • Download latest version of CaptchaMvc from site or nuget (CaptchaMvc.Mvc3 or CaptchaMvc.Mvc4).
  • Add the reference to CaptchaMvc.dll in your project.
  • Include the namespace (@using CaptchaMvc.HtmlHelpers) of the extension method for the views.
Once you do that, you can use extension methods to create a captcha. By default, there are two types of captcha, plain and mathematical.

Methods to create a plain captcha:

  • Html.Captcha(int, params ParameterModel[]) - takes only the length of the characters. The input field is not required. Text of input will be equal to 'Input symbols' and the text of update button will be equal to 'Refresh'.
  • Html.Captcha(string, string, int, params ParameterModel[]) - the input field is not required, text of input will be equal to second parameter, and the text of update button will be equal to first parameter. The length of characters will be equal to the third argument.
  • Html.Captcha(string, string, int, string, params ParameterModel[]) - the input field is required and error message is equals to the fourth parameter, text of input will be equal to second parameter, and the text of update button will be equal to first parameter. The length of characters will be equal to the third parameter.
  • Html.Captcha(int, string, ViewDataDictionary = null, params ParameterModel[]) - the length of characters will be equal to the first parameter. Second parameter takes a partial-view to render captcha. Third parameter takes a ViewDataDictionary for the partial-view.
  • Html.Captcha(int, string, string, ViewDataDictionary = null, params ParameterModel[]) - the length of characters will be equal to the first parameter. Second parameter takes a partial-view to render captcha. Third parameter takes a partial-view to render scripts of captcha. Fourth parameter takes a ViewDataDictionary for the partial-view.

Methods to create a mathematical captcha:

  • Html.MathCaptcha(params ParameterModel[]) - the input field is not required. Text of input will be equal to 'The answer is' and the text of update button will be equal to 'Refresh'.
  • Html.MathCaptcha(string, string, params ParameterModel[]) - the input field is not required, text of input will be equal to second parameter, and the text of update button will be equal to first parameter.
  • Html.MathCaptcha(string, string, string, params ParameterModel[]) - the input field is required and error message is equals to the fourth parameter, text of input will be equal to second parameter, and the text of update button will be equal to first parameter.
  • Html.MathCaptcha(string, ViewDataDictionary = null, params ParameterModel[]) - first parameter takes a partial-view to render captcha. Second parameter takes a ViewDataDictionary for the partial-view.
  • Html.MathCaptcha(string, string, ViewDataDictionary = null, params ParameterModel[]) - first parameter takes a partial-view to render captcha. Second parameter takes a partial-view to render scripts of captcha. Third parameter takes a ViewDataDictionary for the partial-view.
* As you can see, all methods take an array of ParameterModel, its optional parameter, but if you want to change default behavior this parameter may be useful to you. In further examples we will be use it.

How to check the captcha?

There are two ways to do this.
Example of usage attribute to check the captcha:
        [CaptchaMvc.Attributes.CaptchaVerify("Captcha is not valid")]
        [HttpPost]
        public ActionResult MathCaptcha(string empty)
        {
            if (ModelState.IsValid)
            {
                TempData["Message"] = "Message: captcha is valid.";
                return View();
            }

            TempData["ErrorMessage"] = "Error: captcha is not valid.";
            return View();
        }
Example of usage extension method to check captcha:
        [HttpPost]
        public ActionResult Index(string empty)
        {
            if (this.IsCaptchaValid("Captcha is not valid"))
            {
                TempData["Message"] = "Message: captcha is valid.";
                return View();
            }

            TempData["ErrorMessage"] = "Error: captcha is not valid.";
            return View();
        }
This concludes our introduction, further consider how the captcha works and how to extend it.

Comments

Getting a JavaScript error when trying to run the code:
"JavaScript runtime error: '$' is undefined"

declare jQuery script in your layout page, put it in the head tag.

I am getting the same undefined message how did you end up resolving it? Thanks

captcha image is not displaying. why?

Is it possible to wrap JQuery call which starts Captcha into $(function(){})?
In this case i don't need to reference JQuery in the header. My Layout references JQuery at the very bottom of the page, and i want to keep it like this.

Hi,
Which version of CaptachMvc are you using?
Which version of MVC are you using?
Do you have any exception when the captcha is created?

Hi,
Captcha already uses this construction $(function(){}), but for this code is required to define JQuery above it, otherwise you will get an error $ is not defined. To avoid this error you can split the captcha markup and script generation.

Vyacheslav, the same is happening to me, MVC 4, CaptachMvc 4. I have no exceptions, no errors.

In the view (as it's in your examples files)

@using CaptchaMvc.HtmlHelpers

@using (Html.BeginForm())
{

@Html.MathCaptcha("Refresh", "Input", "Is required field.", true)
<br />
<input type="submit" value="Send"/>
}

I appreciate your help. Regards.

Is there a reason why the extensions doesn't defer the execution of the script until jQuery is loaded? Something like the following:

http://stackoverflow.com/a/19458929/201648

OR

https://jadnb.wordpress.com/2011/02/16/rendering-scripts-from-partial-views-at-the-end-in-mvc/

Splitting up the CAPTCHA from the script worked fine, however it becomes a nuisance in some scenarios. e.g. I want to use the CAPTCHA in a partial, and jQuery is loaded at the end of my body in a _Layout.cshtml file.

Found the solution in here, if somebody need it:

http://captchamvc.codeplex.com/discussions/445824

My solution was to add two new routes:

routes.MapRoute("Captcha", "DefaultCaptcha/Generate", new { controller = "DefaultCaptcha", action = "Generate" });

routes.MapRoute("CaptchaRefresh", "DefaultCaptcha/Refresh", new { controller = "DefaultCaptcha", action = "Refresh" });

Thanks, nice work!

Using MathCaptcha, here is my code in my view:

@Html.MathCaptcha("link", "", "Required Field", true)

My controller is using the Attribute method to check against the page. It all works great except when there is a wrong answer. Nothing shows. Do I need to place the TempData object somewhere on the page or is it suppose to be built-in to the Captcha?

Thanks.

Are you using ajax to check the captcha?
Is this example similar to yours?

Can u please tell me how to do captcha client side validation for mvc5

Hi,

I'd like to use IsCaptchaValid extension method, but i can't find that. Where is it?

this.IsCaptchaValid cannot be call.

Hi,
Which version of CaptachMvc are you using?
Here's full path to this method CaptchaMvc.HtmlHelpers.CaptchaHelper.IsCaptchaValid, before this method is called CaptchaMvc.HtmlHelpers.CaptchaHelper.IsCaptchaVerify.
If you are using an older version I recommend the upgrade to the latest.

Hi, how can i set the expiry timeout for a captcha? Its timing out before i finish filling my form.
Thanks

Hi there,
If you use the SessionStorageProvider (by default), it depends on the user's session if the session is invalidated, the values ​​in the captcha will be deleted. You can change the storage provider to the CookieStorageProvider using this code:

protected void Application_Start()
{
    CaptchaUtils.CaptchaManager.StorageProvider = new CookieStorageProvider();
    ....
In this case, a value will be stored in the cookie and will not depend on session.

Can i use Knockout.js (ex: @Html.Captcha(5) new { data_bind="value: captchaValue" })

Where is the documentation for Captcha.Mvc5?

I want to check captcha in a ajax method. Here is my ajax method:

[HttpPost]
[AllowAnonymous]
public ActionResult AjaxLogin(string username, string password, bool remember)
{
ScriptResult scriptResult = new ScriptResult() { Succeed = true };

if (CaptchaMvc.HtmlHelpers.CaptchaHelper.IsCaptchaValid(this,"Captcha is not valid"))
{

}
.
.
.


I always get false in IsCaptchaValid line.
How can I solve this problem?

I'm interested in Ajax Captcha as well. Is this possible?

Try another is set to display none for some reason.

I'm using Split markup and script generation

Hi

I am getting a null reference exception when I try and render the captcha. Oddly this works on my collegues machines. Is there anything in IIS that needs set up? I am using MVC 5 (although oddly the error message has MVC3 in it (assuming this is just the path the code is held at)

[NullReferenceException: Object reference not set to an instance of an object.]
CaptchaMvc.Infrastructure.CaptchaUtils.GetFromSession(String key, Func`1 getItem) in g:\CodePlex\Captcha\CaptchaMvc(Mvc 3)\Infrastructure\CaptchaUtils.cs:224
CaptchaMvc.Infrastructure.SessionStorageProvider.get_DrawingKeys() in g:\CodePlex\Captcha\CaptchaMvc(Mvc 3)\Infrastructure\SessionStorageProvider.cs:144
CaptchaMvc.Infrastructure.SessionStorageProvider.Add(KeyValuePair`2 captchaPair) in g:\CodePlex\Captcha\CaptchaMvc(Mvc 3)\Infrastructure\SessionStorageProvider.cs:52

hi,


i cant figure out, how to validate the captcha, from a custom made ViewModel.

Lets say in the ViewModel are 3 Properties:
1. Username
2. password
3. password confirmation

how do i validate now the captcha in the controller?
how do i access the generated random text?


i really hope you can help me out.


many thanks & all the best
martin

Hi,
Please help me, how to change FontColor, Background, Draw noise of captcha.
Thanks you very much!

Captcha not work in MVC 5, it always return false in if (CaptchaMvc.HtmlHelpers.CaptchaHelper.IsCaptchaValid(this,"Captcha is not valid"))
{

}
Can you help me!
Thanks

Hi,
I want to display captcha on login page if user tipe a wrong password.
At controller method, if i decorate with [CaptchaMvc.Attributes.CaptchaVerify("Captcha is not valid")] and at view i have an if statement that display or not the captcha.
Method from controller return all the time "Captcha is not valid" because ModelState contains the Captcha even if I haven't display it.
How can I display the error message only if captcha is displayed on view and is typed wrong?
Help me please!
Thanks

Why don't you provide a proper project example rather than useless code snippets that mean nothing to a newbie.
Thanks
Tim

Hi Tim,
You can download examples from the project site.

I hate dealing with integrating captcha and this made it much easier thanks!

Why in postback when the form is not valid, the captcha get black screen with a red cross on it?
thanks

how to validate entered captcha in the textbox in button click event client side only

I have problem with Captcha Verification.

MVC POST action looks like this
[CaptchaMvc.Attributes.CaptchaVerify("CaptchaInvalid")]
[HttpPost]
public ActionResult Contact(string name, string phone, string email, string message)
{
var valid= this.IsCaptchaValid("invalid");
var isValid2= ModelState.IsValid;
.....

and valid and isValid2 are false, though text is sent correct ( i see submited captcha value via HttpContext.Request["CaptchaInputText"]).
What could be wrong?

Captcha MVC.MVC4 not displaying on production site. Sometimes after doing page refresh it is displayed but most of the times it shows black image with red cross.

I too am facing the same issue but can't find a solution.
If you have found the solution please share.

Captcha images are not being displayed in Internet Explorer at all times
I even raised the issue in Stackoverlow but no answers yet.

http://stackoverflow.com/questions/33040565/captchamvc-not-working

Hi,

Captcha seems to be not working if referrer information is not enabled in the Browser.
If I disable referrer in the browser then I only get the error bitmap (black background with red cross), generated by GetErrorBitmap. Is there a way to make it work without referrer?

Regards
Michael

how to use captha try again link new imag load please if u everyione know reply me

Hello

Can you please share how to validate captcha using Ajax call instead of Submit button ?

Hi,

Is there any way of editing the html that is generated? I'd like to include an "alt" attribute on the image, and I'd like to remove the "autocorrect" attribute from the input.

Thanks and Kindest Regards,

Ryan

Hi,
I am using IsCaptchaValid Extension method for validating the plain captcha. It works fine in local and QA environments. But it fails for the first time in the Production and works fine on second attempt. Can someone help giving the suggestion?

Thanks
dev

Hi ,
I wanna to use a plain captcha only captcha symbol.
Is it possible to disable 'Input symbols' textbox and 'Refresh' update button.
Can someone help me giving the suggestion?

Hi,
Please upload an example with full source code to use, I am new in MVC and could not use this site!

Hi,

I use jquery and ajax to check the captcha, it validates correctly in the controller, but such issue exists :

1. On the first load, the refresh button work correctly, and also the validation (it checks the entered captcha correctly).
2. But when I entered the incorrect captcha text, the correct error displayed, and after that the refresh button don't work again, and also the validation (I enter the correct captcha but it's stated as invalid).

as note, I return a json object in the controller when validating the captcha. I'm not sure if that's affecting.

I also tried the "split markup and script generation" but it doesn't fix the issue.

Need your help asap :D

thanks

Hi, has your captcha eliminated undesirable words it, like "ASSYOU"?
Thanks!
Daniel

Hello,
I am using CaptchaMVC 3.
I am facing captcha bypass issue in this.
When i send same correct value of ( CaptchaImage , CaptchaDeText and CaptchaInputText ) as below

CaptchaImage = "/DefaultCaptcha/Generate?t=4d776f13b9af46f7a458e3ee1b2b15da"
CaptchaDeText = "4d776f13b9af46f7a458e3ee1b2b15da"
CaptchaInputText = "QTZRC"

it always validate the captcha, even though page is refreshing captcha everytime.

Leave a Reply
*bold*
_italics_
+underline+
* Bullet List
** Bullet List 2
# Number List
## Number List 2
{"Do not apply formatting"}
{code:language} code here {code:language}.
Supports: aspx c#, c#, c++, html, sql, xml
[url:http://www.example.com]