Is it possible to call a method from another class on an ASPX page?

I have some logic in a class called CustomValidation, which I now call in my C # code:

protected void EmailValidator(object source, ServerValidateEventArgs args)
{
    string strInput = args.Value.Trim();
    CustomValidation v = new CustomValidation();
    args.IsValid = v.ValidateEmail(strInput);
}

I would rather call such methods on my ASPX page to simplify things like this:

<asp:CustomValidator OnClick="ValidateEmail" />

However, since ValidateEmail is not in the same class as the page:

'ASP.editusers_aspx' does not contain a definition for 'ValidateEmail' and no extension method 'ValidateEmail' accepting a first argument of type 'ASP.editusers_aspx' could be found (are you missing a using directive or an assembly reference?)

Is there a way to call methods from the CustomValidation class in my ASPX code? I tried the following to no avail:

<%@ Import Namespace="ThisProject.CustomValidation" %>

OnClick="<%= CustomValidation.ValidateEmail()" %>

Here is my use in context:

<asp:TextBox ID="txtEmail" runat="server" Text='<%# Bind("UserEmail") %>' MaxLength="30" />
<asp:CustomValidator ID="vldEmail" runat="server" ControlToValidate="txtEmail" ValidateEmptyText="true" OnServerValidate='<%# RetailCrime.CustomValidation.ValidateEmail((string)(txtEmail.Text)) %>' ErrorMessage='<br /><label class="invisible noplaceholder">&nbsp;</label>Please enter a valid email.' Display="Dynamic" CssClass="validatormessage" />
+3
source share
2 answers

This can be done by creating static delegate.

public class CustomValidator
{
    public static void EmailValidator(object source, ServerValidateEventArgs args)
    {
        string strInput = args.Value.Trim();
        CustomValidation v = new CustomValidation();
        args.IsValid = v.ValidateEmail(strInput);
    }
}

<asp:CustomValidator OnClick="CustomValidator.EmailValidator" />
+4
source

It looks like you have a validator method with which you want to access from at least 2 or more pages. Remember the principle of shared responsibility.

, , . . , "... " ValidateEmail " ...", .

, , . :

public interface IMyValidations { }

public static class MyValidations
{
    public static void ValidateEmail(this IMyValidations target, string input)
    {
        // magic happens here
    }
}

public class MyFirstClass : IMyValidations
{
}

public class MySecondClass : IMyValidations
{
}

,

 MyFirstClass one = new MyFirstClass();
 one.ValidateEmail("foo@bar.com");
 MySecondClass two = new MySecondClass();
 two.ValidateEmail("hello@world.com");

, , , , . , , ?

, . . , , FluentValidations. NuGet .

0

All Articles