Pular para o conteúdo principal

Removendo controle HTML da validação do Validator do Asp.Net com jQuery

Artigo que ensina como gerenciar os controles HTML que estão associados com algum controle Validator do Asp.Net. Utiliza jQuery.

Artigo:

Validators are a great part of the ASP.NET framework: they provide a standardized and easy way to add validation to form fields. But even if the framework provides different kinds of validators, there are so many different validations patterns that sometimes you have to write custom code to match your specific requirements.

I wrote a post a few months ago about how to write a custom validator for a Checkbox list, but I was dealing with a completely new validation pattern. But what if I only want to enable the validation of certain field based on certain conditions? Or if I want to validate based on an event that is not the OnChange event of the form field? And all of this while keeping the standard validation logic?

If the condition can be determined in the code-behind it's easy:

//Disable server side validation
myRequiredFieldValidator.Enabled = false;
//Disable client side validation
myRequiredFieldValidator.EnableClientScript = false;

But what if I want to enable the validator from javascript? I didn't find anything online about this so I debugged the ASP.NET js validation library to look for the method that enables the validation, and for the one that forces the validation check.
Enable a validator via javascript

The method to enable or disable a validator is:

function ValidatorEnable(val, enable)

where val is the reference to the element that the validator uses to render the error message, and enable is a boolean to tell the method whether to enable or disable the validation.
Force a validation via javascript

In case you want to ask to a validator to do his job:

function ValidatorValidate(val, validationGroup, event)

val is again the reference to the validator , validationGroup is the name of the validation group of the element that is triggering the validation, event is the reference to the event that triggered the validation. But only the first parameter is useful when you want to force the validation, since the others are used only by the standard validation of ASP.NET.
A real life example

Let's see a example from the code I'm writing for one of the new features of Subtext.
Imagine you have this snippet of HTML code:


audio/mpeg
audio/wma
Other


ControlToValidate="txbOtherMimetype" ForeColor="#990066"
ErrorMessage="You have to specify a custom mimetype." />

And you want to enable the valOtherMimeTypeRequired validator only when the option selected in the drop down is "other".

Using jQuery here is the javascript code to do the job:



Notice the <%= ddlMimeType.ClientID %> to select a server-side control using the automatically generated client ID and the $("#elemendId")[0] to get the real DOM element and not the jQuery wrapper around it.

And in case I wanted to force the validation I should have written:

ValidatorValidate($("#<%= valEncOtherMimeTypeRequired.ClientID %>")[0]);

It took me a while to find out this method name. I hope this will save you a bit of the time I spent hunting down the names using Firebug.

Fonte: http://codeclimber.net.nz/archive/2008/05/14/how-to-manage-asp.net-validation-from-javascript-with-jquery.aspx

Comentários

Postagens mais visitadas deste blog

A batalha por uma SafeKid (Unicamp)

Figura 1 - Cadeira Safekid (Unicamp) Nas consultas usando a ferramenta de busca do Google obtive os seguintes link para a tal cadeira. 1- http://revistacrescer.globo.com/Crescer/0,19125,EFC1010380-2213-2,00.html 2- http://www.ibiubi.com.br/produtos/cadeira-cinto-de-seguran%c3%a7a-safekid-projetado-pela-unicamp+beb%c3%aas-e-crian%c3%a7as+cadeiras/IUID4138740/ 3- http://compras.hsw.uol.com.br/assento-infantil-guia.htm 4- http://produto.mercadolivre.com.br/MLB-123086053-cadeiracinto-de-seguranca-safekid-projetado-pela-unicamp-_JM a própria! só que venda finalizada. Foi então que resolvi procurar no Bing (Microsoft) www.bing.com. Também não encontrei! Rs Encontrei algumas parecidas a preços imbatíveis, mas fora do país. 1- http://www.magazineluiza.com.br/produto/index_Produto.asp?Produto=1766074&linha=BB&Setor=CADA&modelo=08 2- http://www.precomania.com/search_attrib.php/page_id=1990/st=page/page=1 Mas foi no Yahoo buscas que eu encontrei a dita cuja. Quero dizer, um possível ...

Driver para Receptor de TV Digital da Multilaser RE003

Email recebido da central de atendimento da Multilaser para resolver problema de funcionamento do receptor digital em Windows 7. --------------------------------------------------------------------------------- Prezado(a) Cliente, Primeiramente pedimos desculpas por quaisquer transtornos causados. Segue anexo manual passo a passo para a instalação do RE003. Conseguimos desenvolver um novo software para o aparelho, pois o enviado no cd não estava conseguindo localizar canais. Peço a gentileza de seguir o passo a passo e me informar se conseguiu utilizar o produto. Os drivers que irá precisar estão disponíveis no link http://tinyurl.com/j3w3svn Os drivers que irá precisar estão disponíveis no link  http://tinyurl.com/j3w3svn Os drivers que irá precisar estão disponíveis no link  http://tinyurl.com/j3w3svn Instale os drivers e o software Presto! Serial: EVALUATION

EmguCV DLL Not Found Exception -Unable to find cvextern?

Eu também tive os mesmos problemas. Neste fórum emgucv , não sei por que cvextern.dlldo emgucv 3.4.3 não é possível carregar cvextern (porque não é possível encontrar cvextern), e você permitiu usar o arquivo cvextern.dlldo emgucv 3.4.2 (certifique-se de escolher x64 / x86), copie /bin/Debuge este arquivo é encontrado automaticamente /bin/Debug/x86ou /bin/Debug/x64quando você termina de construir o programa no Visual Studio.  O Erro:  The type initializer for 'Emgu.CV.CvInvoke' threw an exception. : Unable to load DLL 'cvextern': The specified module could not be found. (Exception from HRESULT: 0x8007007E)  Para resolver o problema copia a pasta x64 ou x86 para dentro da pasta bin da aplicação. Ou copie os arquivos para dentro da pasta bin da aplicação WCF.