Elegant way to make CustomValidator work with ValidationSummary messagebox

后端 未结 7 2243
耶瑟儿~
耶瑟儿~ 2020-12-14 08:40

I have run into this problem before but never quite solved it. I have a form with several validators and also a CustomValidator.



        
7条回答
  •  情书的邮戳
    2020-12-14 09:28

    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.

    *
       //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", ""); 
    
        }
    
    }
    

提交回复
热议问题