Изящный способ заставить CustomValidator работать с ValidationSummary messagebox

В вашем коде есть две проблемы, одна из которых приводит к ошибке, которую вы получаете.

  1. Вы должны включить свой модуль в здание здесь component = DaggerAppComponent.create();
  2. Кинжал НЕ внедряется в частные поля.

Пример p1:

DaggerAppComponent.builder()
   .networkModule(new NetworkModule())
   .build()
19
задан Alfero Chingono 1 May 2009 в 15:00
поделиться

4 ответа

Try using a ValidationGroup property across all your validators and the ValidationSummary.

EDIT: Another possibility could be the Server Validation Code

args.IsValid = (!CampaignRegistration.IsMemberRegistered(args.Value));

if CampaignRegistration.IsMemberRegistered(args.Value) is returning false, "!" is making it true and therefore making it valid. I think you should get rid of the "!" as follows:

args.IsValid = CampaignRegistration.IsMemberRegistered(args.Value);

UPDATE: In order for the ValidationSummary to display your custom validator message in a messagebox, you need to have ClientValidationFunction Code. If you need to display just the summary without a popup, this is not needed.

<asp:CustomValidator ID="cvMemberNum" runat="server" 
    CssClass="ValidationMessage" Display="Dynamic"
    ControlToValidate="txtMemberNum" ValidateEmptyText="false"
    OnServerValidate="cvMemberNum_Validate"
    ClientValidationFunction = "ClientValidate"  
    ErrorMessage="This membership number is already registered">*</asp:CustomValidator>
   //JavaScript Code.
   function ClientValidate(source, args)
   {         
      args.IsValid = false; //you need to add validation logic here
   }

MORE: If you don't want to do ClientSide Validation, try this trick to show the alert. Make this change to your CustomValidator ServerValidate method:

protected void cvMemberNum_Validate(object source, ServerValidateEventArgs args)
{
    bool isValid = true;
    try
    {
        isValid  = (!CampaignRegistration.IsMemberRegistered(args.Value));
    }
    catch
    {
        isValid = false;
    }
    args.IsValid = isValid;

    if(!isValid)
    {
       if(!Page.IsClientScriptBlockRegistered("CustomValidation")) 
         Page.RegisterClientScriptBlock("CustomValidation", "<script>alert('This membership number is already registered');</script>"); 

    }

}
10
ответ дан 30 November 2019 в 04:25
поделиться

You should write a property

ValidationGroup="ValidationSummary1"

at every validator in your case.

Also check if your page has

AutoEventWireup="true"
1
ответ дан 30 November 2019 в 04:25
поделиться

Параметр ShowMessageBox полностью на стороне клиента, поэтому он будет оцениваться только в том случае, если вы установили ClientValidationFunction в CustomValidator ].

Вы также можете подделать его, зарегистрировав скрипт, который выдает предупреждение, поэтому, когда вы вернетесь из проверки сервера, он выдаст сообщение об ошибке. Это можно либо зарегистрировать в методе ServerValidate (согласно @Jose Basilio ), либо вы можете вызвать следующий метод во время события PreRender, чтобы зарегистрировать всплывающее окно со всеми недействительными валидаторами на странице:

    /// <summary>
    /// Registers a script to display error messages from server-side validation as the specified <see cref="UserControl"/> or <see cref="Page"/> loads from a postback.
    /// </summary>
    /// <remarks>
    /// Must be called in the PreRender if used to validate against the Text property of DNNTextEditor controls, otherwise Text will not be populated.
    /// Must set the ErrorMessage manually if using a resourcekey, otherwise the resourcekey will not have overridden the ErrorMessage property.
    /// </remarks>
    /// <param name="ctrl">The <see cref="UserControl"/> or <see cref="Page"/> which is being posted back.</param>
    /// <param name="validationGroup">The validation group against which to validate.</param>
    public static void RegisterServerValidationMessageScript(TemplateControl ctrl, string validationGroup)
    {
        if (ctrl != null && ctrl.Page.IsPostBack)
        {
            ctrl.Page.Validate(validationGroup);
            if (!ctrl.Page.IsValid)
            {
                StringBuilder errorMessage = new StringBuilder("<script language='javascript'>alert('");
                for (int i = 0; i < ctrl.Page.Validators.Count; i++)
                {
                    IValidator validator = ctrl.Page.Validators[i];
                    if (!validator.IsValid)
                    {
                        errorMessage.Append("- " + validator.ErrorMessage);
                        if (i < ctrl.Page.Validators.Count - 1)
                        {
                            errorMessage.Append(@"\r\n");
                        }
                    }
                }

                errorMessage.Append("');</script>");
                ctrl.Page.ClientScript.RegisterStartupScript(typeof(IValidator), "validationAlert", errorMessage.ToString(), false);
            }
        }
    }
7
ответ дан 30 November 2019 в 04:25
поделиться

У меня сработало:

<asp:CustomValidator runat="server" ID="cv" 
ClientValidationFunction="ValidateFunction"
ErrorMessage="Default error
message">*</asp:CustomValidator>

<script type="text/javascript">
function ValidateFunction(sender, args) 
{

var msg ='';
var formValid = true;

[various checks setting msg and formValid]

if (msg.length > 0) { sender.errormessage = msg; }
args.IsValid = formValid;

}
</script>
1
ответ дан 30 November 2019 в 04:25
поделиться
Другие вопросы по тегам:

Похожие вопросы: