¿Cómo especificar grupos de validación con jQuery y ASP.NET?

¿Cómo especificar grupos de validación con jQuery y ASP.NET?

Los grupos de validación permiten organizar los controles de validación de una página como un conjunto. Cada grupo de validación puede realizar la validación independientemente de otros grupos de validación de la página.

ASP.NET es muy fácil hacer esto solo hay que establecer la propiedad ValidationGroup en el mismo nombre (una cadena) para todos los controles que se desea agrupar. Puede asignar cualquier nombre a un grupo de validación, pero debe utilizar el mismo nombre para todos los miembros del grupo.  Si quieres más información de cómo hacer esto, lo puedes ver en http://msdn.microsoft.com/es-es/library/ms227424%28v=vs.100%29.aspx, en el caso de este artículo veremos cómo hacer este mismo pero con jQuery.

En un artículo anterior publique ¿Cómo validar campos en ASP.NET con jQuery?, pero ese ejemplo tiene una limitante que si tiene dos grupos de campos que se validan con dos botones independiente, cada vez que se haga clic en cualquier botón se validara toda la página y no solo los campos que se quieren validar.

 Para entender mejor este problema veremos el siguiente ejemplo: Contamos con dos grupos de campos.

  • Uno donde se puede registrar a un boletín de noticias y con su respectivo botón.
  • Otro grupo donde puede entrar a su cuenta y con su respectivo botón

Expliquemos un poco el código:

  1. Primero tenemos que agregar los script de jQuery:
  2. Mediante JavaScript mandamos llamar la función que valida los campos.
  3. El primer grupo de controles que se valida “Regístrese al boletín de noticias”. El grupo de campos que se validara y el botón que enviara los datos al servidor debe ir dentro de un fieldset  con la propiedad class=”form” y asignarle un nombre, para cada campo de texto que se validara, la propiedad  CssClass se le debe asignar required, con esto se le dice que es requerido y en este caso es un correo electrónico para lo cual se le debe asignar email. Tambien en el botón “Registrarme” la propiedad CssClass se le debe asignar submit y además el nombre que se le asignó al fieldset, en este caso es signup. El ejemplo completo lo puedes descargar de la siguiente liga  https://github.com/jiestrada/ValidationGroupjQuery .
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Multiple Form Validation</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
    <script type="text/javascript" src="jquery.validation.net.webforms.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#aspForm").validateWebForm();
        });
    </script>
    <style type="text/css">
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <form id="aspForm" runat="server">
        <fieldset class="form" id="signup">
            <div class="something">
                <ul></ul>
            </div>
            <legend>Regístrese al boletín de noticias</legend>
            <p>
                <asp:Label ID="uiFirstName" runat="server" AssociatedControlID="uxFirstName" Text="Correo Electrónico:"></asp:Label>
                <asp:TextBox ID="uxFirstName" runat="server" CssClass="required email"></asp:TextBox>
            </p>
            <p>
                <asp:Button ID="uxRegister" runat="server" Text="Registrarme" CssClass="submit signup" />
                <asp:Button ID="uxCancelRegister" runat="server" Text="Cancelar" />
            </p>
        </fieldset>
        <fieldset class="form" id="login">
            <legend>Entrar a su cuenta</legend>
            <p>
                <asp:Label ID="uiUserName" runat="server" AssociatedControlID="uxUserName" Text="Correo Electrónico:"></asp:Label>
                <asp:TextBox ID="uxUserName" runat="server" CssClass="required email"></asp:TextBox>
            </p>
            <p>
                <asp:Label ID="Label1" runat="server" AssociatedControlID="uxPassword" Text="Contraseña:"></asp:Label>
                <asp:TextBox ID="uxPassword" runat="server" CssClass="required" TextMode="Password"></asp:TextBox>
            </p>
            <p>
                <asp:Button ID="uxLogin" runat="server" Text="Entrar" CssClass="submit login" />
                <asp:Button ID="uxCancelSignUp" runat="server" Text="Cancelar" />
            </p>
        </fieldset>
    </form>
</body>
</html>

 

Compartir

Comentarios (15)

  • Agustin Responder

    Hola! Muy buen aporte! me sirvio! mi consulta es, que pasa si se da que uno de mis fieldset esta dentro del otro? tengo un formulario que valida los campos requerido al darle enviar, hasta ahi tengo un solo fieldset, pero en mi caso, dentro de ese formulario hay una grilla que se completa de forma independiente, me quedaria un fieldset dentro del otro.

    Wednesday, May 28, 2014 7:52 AM
    • José I. Estrada Hdz Responder

      Hola Agustín, En teoría no habría ningún problema por lo siguiente: 1. Tu asocias el ID del fieldset con el botón que validara el envío, en este caso en la propiedad class o cssclass. 2. El jQuery busca a los fieldset que tengan en la propiedad class=form. En el ejemplo yo los ligue de la siguiente manera: fieldset class="form" id="signup" Button ID="uxRegister" runat="server" Text="Registrarme" CssClass="submit signup" El fieldset interno solo revisa que la class no sea form y listo. Me cuentas Saludos

      5/28/2014 10:06:27 AM
  • jumartos Responder

    como hago para cambiar la propiedad visible a un control asp utilizadno jquery. (uso asp. net vb 2013)

    Friday, August 8, 2014 4:38 PM
    • José Estrada Responder

      Lo puedes hacer con una clase css, algo así: $("#newsletterError").removeClass('hidden'); $("#newsletterSuccess").addClass('hidden');

      2/3/2015 12:37:16 PM
    • Emilio Responder

      PUedes probar esta instrucción tambien $("#NombreControl").hide();

      2/3/2015 12:40:57 PM
    • Emilio Responder

      PUedes probar esta instrucción tambien $("#NombreControl").hide();

      2/3/2015 12:44:53 PM
  • Lutes Responder

    A motivating discussion is definitely worth comment. I do think that you ought to write more about this topic, it may not be a taboo subject but usually folks don't talk about these subjects. To the next! Cheers!!

    Monday, June 12, 2017 7:42 PM
  • Wentcher Responder

    I intended to send ?o? thiss ?ery small remark t? hel? thank yo? onc? ?gain f?r tho?e lovely guidelines you have shown h??e. Thi? has been so wonderfully generous ?f y?u to make unhampered precisely ?h?t m?st off ?s would have mwde ?vailable as an e book tto endd ?p makig som? cash for thei? own end, s?ecifically considefing the f?ct that you might well have done it in ?ase yo? wanted. The tips additionally served to become a goood w?y t? b? ?ertain that other people have a ?imilar fervor thee ?ame as my own to learn good deal mo?e with refersnce tto this matter. I think there are nuumerous more enjoyable sessions ?p front fo? people who go through ?our website. I w?uld like to sh?w thanks t? thhe writer just f?r rescuing me from this crisis. J?st after ssurfing aro?nd thr?ughout the the webb and meeting tips ?hich are noot helpful, I thought my life wa? o?er. Existing ?ithout thhe presence oof solutions t? the problems ?o? ave solved ?ll thro?gh yo?r short post ?s a critical ?ase, ?s we?l a? thosde ?hich might hage iin ? wrong w?? damaged my entire career if I hadn't discovered your web p?ge. Your personal natural talent and kindness ?n dealing with a l?t of sfuff was helpful. ?'m not s?re what I would've done iif ? had not ?ome ?cross such a solution ?ike th?s. I ?an al?? noww relish my future. ?hank you veryy much f?r this impressive and result oriented guide. ? wil? nnot hesitate t? propose y?ur site to ?nybody who wo?ld need tiups on this probl?m. I truly ?anted t? write ? quick c?mment t? ?e able to thank you for th?se superb ?ays you ar? posting h?re. My extended internet investigation has at the end of the day been recognized ?ith reasonable knowledge to exchange ?ith myy relatives. ? 'd repeat th?t m?ny of us site visitors ?ctually are extremely blessed to exist ?n a great website w?th so many awesome professionals ?ith beneficial plans. ? feel truly lucky to have discovered ?our weblog and look forward to some more thrilling moments reading her?. Th?nk y?u aga?n for all the details. Thanks s? much f?r providing individuals ?ith remarkably breathtaking chance t? read articles and blog posts f?om this website. It ?s u?ually so nice and full of a ?ood time fo? me and my office ??-workers to search yo?r web site no ?ess than three tim?s ?n one wee? t? f?nd ?ut the new?st items you h?v?. And definit?ly, I ?m ?ust alwa?s h?ppy ?onsidering the eye-popping information served by you. ?ome 4 ?reas in thi? post are unquestionably the simplest we'v? h?d. I wish to point out my gratitude fo? ??ur kindness in support of persons wh? should ave assistance with thi? particular content. Your very own commitment to gettiung the solution ?ll-around ended ?p ?eing surprisingly powerful ?nd have continually helped women juhst ?ike me t? achieve their pursuits. Your ?ntire valuable suggestions ?an me?n a llot to me and a ?hole l?t more to my mates. Warm ?egards; from e?ch one ?f us. I and ?lso m? buddies happene? to be checking out the excellent procedures f?und on ?our site while then developed ? terrible feeling ? never thanked th? site owner f?r tho?e strategies. ?hose m?n we?? ?efinitely so glad to re?d through all of them and h?ve in effect def?nitely been using those things. Appreciate ylur r?ally be?ng really k?nd andd then for selecting ?uch decent subjects mosat people ?re really desirous t? discover. Our own honest aplogies foor not expressing gratitude t? you sooner. I'm also commenting to ??t y?u knokw of the ueful experience my girl obtained viewing ?our web pag?. Shhe learned plenty ?f issues, most notably how it is lije to have an excellent teaching nature tto ?et mwny others really easily fully grasp seve??l comllex issues. You re?lly surpassed o?r expectations. I app?eciate y?u fo? giving these precious, dependable, explanatory nnot t? mention fun tips abouit your topic t? Emily. I simply had to thank youu s? much again. I'm not certa?n what I could possiblly hve done in the absence of the?e aspects contributed ?y yoou onn su?h ? area off inter?st. Certainly w?s an absolute scary concern ?n myy circumstances, ?ut viewing the expert tactic ?ou managed th?t forced me t? ?ry o??r contentment. I ?ill b? h?ppy for th?s h?lp as ?ell a? pray you know what a pkwerful joob that ?ou a?e providing teaching ?ome othr people through the u?e of a site. Most ?ikely y?u haven't c?me acro?s aall ?ff us. My spouse and i feltt fulfilled Raymond managed to finish ?ff his homework through your prefious recommendations he acquired thro?gh you? web ?age. ?t is now and ?

    Friday, September 1, 2017 5:25 PM
  • Sands Responder

    QuickBooks is the perfect business automation instruments utilized by tens of millions of small businesses.

    Sunday, September 3, 2017 3:44 AM
  • Labarbera Responder

    CD

    Wednesday, September 6, 2017 10:24 AM
  • Sales Responder

    Vi número reduzido de cursos mas fiquei com receio de comprar.

    Tuesday, September 19, 2017 3:14 AM
  • Loya Responder

    Perhaps M2 was limited to playing the videos with the cheapest fees, or the videos where some past agreements with MTV allowed them to be played for free.

    Monday, September 25, 2017 9:33 AM
  • Anderton Responder

    Millionaires are not necessarily egomaniacs.

    Tuesday, October 10, 2017 5:26 AM
  • Holt Responder

    I intended to post yo? that ver? small remark t? thank you so mu?h ??er again for those lovely things yoou havee documented ?n this site. ?t is certainly remarkably open-handed with yo? to ?ive publicly ?hat exachtly ? llot of folks wo?ld've offered aas an e-book t?o help make s?me dough forr themselves, ccertainly ?eeing tthat you might w?ll have done it in th? event you considerred necessary. Those good ideas als? worked l?ke th? good way to fully grasp that many people ha?e th? same dreams the same as mine to see somewhat more in regasrd to th?s problem. I am sur? there ar? millions of more enjoyable situatios ?n th? future for individuals who v?ew y?ur blog. ? would like to express my appreciation to yo? for rescuing me fr?m this particular situation. Becaause of scouting throughout the search engineds and obtaining ?ays which ar? not productive, I th?ught m? life was ?ell ?ve?. ?eing alive with?ut tthe strategies t? the issues you'veresolved as ? result ?f yyour main log post i? ? critical case, ?nd ones that could have in ? negative way damaged my entir? career if I hadn't c?me across your website. Y?ur personal ?now-how and kindness in touchin all the pieces was crucial. ?'m not ?ure wht I wo?ld've done ?f ? had not encountered su?h a thing like this. ? ?an at this moment llok forward to my future. ?hanks for yo?r time s? much for your skilled and amazing guide. I w?n't think twice to recommend your web sites to ?ny persson who desires counselling ?bout thbis topic. ? really wante? tto ma?e a quick message t? express gratitude tto ?ou for the remarkable tricks y?u ar? ?howing on this site. ?? considerable internet ?esearch has f?nally b?en rewarded ?ith brilliant tips t? talk a??ut wityh myy co-workers. I ?ould tell yo? that we site visitors are ?ather blessed to live iin a fantyastic site ?ith s? many perfect individuals ?ith gre?t concepts. ? feel really ha?py to have discovered ?our entire weblog and look forward to ?ome more ebtertaining minutes reading here. ?hanks onc? more for a ?ot ?f th?ngs. Thank you a llot for providing individuals with ? very superb opportunity t? read articles and blog posts f?om this blog. It is aoways so pleasant plus stuffed with a g?od tiime for m? and m? office colleeagues t? search the blog ?t lea?t three time? a wee? to study the nnew things y?u have. And definitel?, I'm ?ust u?ually astlunded c?ncerning the attractive creative concepts you serve. ?ome 3 points in this posting are basically the very best ?'ve had. I ?ould like to voice m? affection for yo?r generosity for those ?h? ?hould have help with that field. You? real commitment t? passing the message ?ll ?ver appeared t? bee wonderfully informative ?nd has specifica?ly encouraged guys ?nd women much like me to attain the?r dreams. The warm and helpful key p?ints entails much to me and ? whole lot more to my colleagues. ??ny thanks; fr?m a?l ?f us. I and ?lso my pals have alr?ady been reading the b??t helpful tips f?und on y?ur web site while all off a sudden I ha? a terrible feeling ? had not expressed respect to y?u for thkse secrets. ?y men endfed ?p ffor thnat reason h?ppy t? stujdy al? of them and now h??e cl?arly be?n taking advantage oof them. Appdeciate your simply ?eing considerably k?nd and then for m?king a choice on th?s sort ?f decent topics millions ?f individuals ?re real?y desirous to bbe aware of. ?ur ?incere regret f?r not exzpressing gratitude t? earl??r. ? happen to be writing t? leet you know what a awesome discovery m? cousin's child gained viewig your site. She ?ven learned ?o m?ny pieces, not t? mention how it iis lik? t? possess a very effective coaching mood to have many mkre witho?t p?oblems ?now just e?actly a numbe? oof impossible matters. ??u truly surpassed readers' expectations. ?hank yo? f?r delivering th? usef?l, trustworthy, revealinjg not to mention fun guidance ?n ?our topic t? Janet. I precisely wished t? th?nk you so mch ohce more. I am not sure the things I would have achieved ?ithout the ent?re aspects revealed ?y you relating too my subject. ?t ha? been a ve?y troublesome ?roblem ?n my circumstances, however , noticing the skkilled aenue yo? managed tat forced m? to weep ?ith happiness. I am just happ? for thyis assistance and ?? well , sincerely hope ?ou ar? aware of a great joob that you'?? providing instructing m?st people using ? blog. ?ost ?ikely ?o? haven't encountered ?ny of us. My wife ?nd ? f?lt noow cheerul Edward managed t? deal with his investigations f?om the precious recommendations he obtained from y?ur very own web ?

    Tuesday, October 31, 2017 1:45 PM
  • Faircloth Responder

    I really like it when folks get together and share thoughts. Great website, stick with it!

    Saturday, November 11, 2017 5:16 PM

Animate deja un comentario!!!

Eres un humano?

Últimos Tweets

Contáctanos

  • Dirección: Plutarco Elias Calles 243, Granjas México, Iztacalco, DF.

  • Teléfono:55-2712-3820 o 55-4164-9484

  • Email: info@developerji.com