Meddelande

Minska
No announcement yet.

Captchakontroll (ASP.NET)

Minska
X
  • Filter
  • Klockan
  • Show
Clear All
new posts

  • Captchakontroll (ASP.NET)

    Efter mycket letande så bestämde jag mig för denna Captchakontroll för att den var enkel och motsvarade mina behov.
    Men för att göra den mer användbar så skapade jag en "CaptchaValidator" som ärver CustomValidator och validerar en textbox både serverside och clientside på ett bräde. Och en till bra sak är att jag kan sätta de olika delarna (bilden,textboxen och validatorn) vart som helst på sidan.
    Hur implementeras nu detta?

    1. Ladda ner kontrollen här (skapa ett medlemsskap om du inte är medlem).
    Använd alla filer utom default.aspx med tillhörande codefile/codebehind.
    2. Lägg till en bild på sidan med JpegImage.aspx som src.
    3. Lägg till en textbox med id på sidan.
    4. Lägg till CaptchaValidatorn och sätt önskade egenskaper och textboxens id som "controltovalidate".
    ex.
    [kod]<img src="JpegImage.aspx" alt="" id="captcha" width="120" height="50" />
    <asp:TextBox ID="captchaText" runat="server" Width="35" />
    <cc1:CaptchaValidator ID="CV1" runat="server" ControlToValidate="captchaText" CaptchaLength="4"
    ValidationGroup="myForm" ErrorMessage="Siffrorna du skrev stämmer" ClientErrorMessage="Det skall vara fyra siffror" Text='<img src="/icons/warning.gif" width="12" height="12" alt="" />' />[/kod]


    VB:[kod]<ToolboxData("<{0}:CaptchaValidator runat=""server""></{0}:CaptchaValidator>"), DefaultProperty("Text")> _
    Public Class CaptchaValidator
    Inherits CustomValidator
    Private random As New Random()
    Private _CaptchaLength As Integer
    Private _ClientErrorMessage As String
    Private _CaptchaImageText As String = Nothing
    Dim txtBox As TextBox

    Sub New()
    Me.CaptchaLength = 5
    Me.ValidateEmptyText = True
    Me.ClientErrorMessage = "Captcha error"
    End Sub

    Public Property CaptchaLength() As Integer
    Get
    Return _CaptchaLength
    End Get
    Set(ByVal value As Integer)
    _CaptchaLength = value
    End Set
    End Property

    Public Property ClientErrorMessage() As String
    Get
    Return _ClientErrorMessage
    End Get
    Set(ByVal value As String)
    _ClientErrorMessage = value
    End Set
    End Property

    Protected Sub _OnServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs) _
    Handles Me.ServerValidate
    args.IsValid = Boolean.Parse(txtBox.Text = Me._CaptchaImageText)
    End Sub

    Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me._CaptchaImageText = String.Concat(Me.Context.Session.Contents.Item("CaptchaImage Text"), String.Empty)

    txtBox = DirectCast(me.FindControlByID(Me.Page.Controls, Me.ControlToValidate), TextBox)
    txtBox.MaxLength = Me.CaptchaLength
    txtBox.ValidationGroup = Me.ValidationGroup

    If Not Me.Page.IsPostBack Then
    Me.Context.Session.Contents.Add("CaptchaImageText", GenerateRandomCode(Me.CaptchaLength))
    Else
    If txtBox.Text <> Me._CaptchaImageText Then
    Me.Context.Session.Contents.Add("CaptchaImageText", GenerateRandomCode(Me.CaptchaLength))
    End If
    End If
    End Sub

    Protected Overrides Sub CreateChildControls()
    Controls.Clear()

    'Add a RegularExpressionValidator to this control
    Dim rev As RegularExpressionValidator
    rev = New RegularExpressionValidator
    rev.SetFocusOnError = True
    rev.ValidationExpression = String.Format("^[0-9]{{{0}}}$", Me.CaptchaLength)
    rev.ID = "REV" & Me.ID
    rev.ValidationGroup = Me.ValidationGroup
    rev.ControlToValidate = Me.ControlToValidate
    rev.Text = Me.Text
    rev.ErrorMessage = Me.ClientErrorMessage

    'Add a RequiredFieldValidator to this control
    Dim rfv As RequiredFieldValidator
    rfv = New RequiredFieldValidator()
    rfv.ID = "RFV" & Me.ID
    rfv.ValidationGroup = Me.ValidationGroup
    rfv.ControlToValidate = Me.ControlToValidate
    rfv.Text = Me.Text
    rfv.ErrorMessage = Me.ClientErrorMessage

    Me.Controls.Add(rfv)
    Me.Controls.Add(rev)
    End Sub

    ' Returns a string of random digits.
    Private Function GenerateRandomCode(ByVal l As Integer) As String
    Dim s As String = String.Empty
    For i As Integer = 0 To l - 1
    s = String.Concat(s, Me.random.Next(10).ToString())
    Next
    Return s
    End Function

    Private Function FindControlByID(ByVal controls As ControlCollection, ByVal id As String) As Control
    Dim found As Control = Nothing
    For Each control As Control In controls
    If control.ID = id Then
    Return control
    End If
    If control.HasControls() Then
    found = FindControlByID(control.Controls, id)
    If found IsNot Nothing Then
    Return found
    End If
    End If
    Next
    Return found
    End Function

    End Class
    [/kod]

    Maskinöversatt till C#:[kod][ToolboxData("<{0}:CaptchaValidator runat=\"server\"></{0}:CaptchaValidator>"), DefaultProperty("Text")]
    public class CaptchaValidator : CustomValidator
    {
    private Random random = new Random();
    private int _CaptchaLength;
    private string _ClientErrorMessage;
    private string _CaptchaImageText = null;
    TextBox txtBox;

    public CaptchaValidator()
    {
    this.CaptchaLength = 5;
    this.ValidateEmptyText = true;
    this.ClientErrorMessage = "Captcha error";
    }

    public int CaptchaLength {
    get { return _CaptchaLength; }
    set { _CaptchaLength = value; }
    }

    public string ClientErrorMessage {
    get { return _ClientErrorMessage; }
    set { _ClientErrorMessage = value; }
    }

    protected void _OnServerValidate(object source, ServerValidateEventArgs args)
    {
    args.IsValid = bool.Parse(txtBox.Text == this._CaptchaImageText);
    }

    public void Page_Load(object sender, System.EventArgs e)
    {
    this._CaptchaImageText = string.Concat(this.Context.Session.Contents.Item("CaptchaIma geText"), string.Empty);

    txtBox = (TextBox)this.FindControlByID(this.Page.Controls, this.ControlToValidate);
    txtBox.MaxLength = this.CaptchaLength;
    txtBox.ValidationGroup = this.ValidationGroup;

    if (!this.Page.IsPostBack) {
    this.Context.Session.Contents.Add("CaptchaImageText", GenerateRandomCode(this.CaptchaLength));
    }
    else {
    if (txtBox.Text != this._CaptchaImageText) {
    this.Context.Session.Contents.Add("CaptchaImageText", GenerateRandomCode(this.CaptchaLength));
    }
    }
    }

    protected override void CreateChildControls()
    {
    Controls.Clear();

    //Add a RegularExpressionValidator to this control
    RegularExpressionValidator rev;
    rev = new RegularExpressionValidator();
    rev.SetFocusOnError = true;
    rev.ValidationExpression = string.Format("^[0-9]{{{0}}}$", this.CaptchaLength);
    rev.ID = "REV" + this.ID;
    rev.ValidationGroup = this.ValidationGroup;
    rev.ControlToValidate = this.ControlToValidate;
    rev.Text = this.Text;
    rev.ErrorMessage = this.ClientErrorMessage;

    //Add a RequiredFieldValidator to this control
    RequiredFieldValidator rfv;
    rfv = new RequiredFieldValidator();
    rfv.ID = "RFV" + this.ID;
    rfv.ValidationGroup = this.ValidationGroup;
    rfv.ControlToValidate = this.ControlToValidate;
    rfv.Text = this.Text;
    rfv.ErrorMessage = this.ClientErrorMessage;

    this.Controls.Add(rfv);
    this.Controls.Add(rev);
    }

    // Returns a string of random digits.
    private string GenerateRandomCode(int l)
    {
    string s = string.Empty;
    for (int i = 0; i <= l - 1; i++) {
    s = string.Concat(s, this.random.Next(10).ToString());
    }
    return s;
    }

    private Control FindControlByID(ControlCollection controls, string id)
    {
    Control found = null;
    foreach (Control control in controls) {
    if (control.ID == id) {
    return control;
    }
    if (control.HasControls()) {
    found = FindControlByID(control.Controls, id);
    if (found != null) {
    return found;
    }
    }
    }
    return found;
    }

    }[/kod]
    3
    Exakt vad jag behövde
    66.67%
    2
    Bra-å-ha-sak
    33.33%
    1
    Host...kastas i papperskorgen
    0.00%
    0
    Last edited by Jesper T; 2008-02-06, 18:41.
    Vänligen Jesper
    Etisk kommunikation
Working...
X