Grouping Validators by Submit Button

Rate It (1)

Last post 05-25-2005 10:06 AM by Sebastian. 11 replies.

Sort Posts:

  • Grouping Validators by Submit Button

    07-31-2003, 3:16 PM
    • Loading...
    • jgallant
    • Joined on 06-27-2002, 3:22 PM
    • Posts 31
    Summary

    One weakness of the .NET validators is that they take an all or nothing approach to validation. If you have a validators on the page and you invoke validation every validator will be evaluated if it is enabled no matter which button was clicked.

    This posed a problem for me while recently developing a new product. The requirement was that there should always be a login element in the upper left hand corner which has required and regular expression field validators. Everything was fine until I add a registration page which also had validators. I obviously needed some separation between the two, because when the user clicked the "Login" button the webform was firing the "Registration" field validators.

    Essentially, what I did to get around this is modified the WebUIValidation.js file and created a derived page of the System.Web.UI.Page class in which I overrided the Page_Load and Validate methods, as well as added a ValidatorAssignments property.

    Modifying both the client (.js) file and the server files ensures that the validation will function as desired both on the client and server.

    WebUIValidation.js Modifications

    The modification to this file are done in the Page_ClientValidate function.

    var Page_InitValidators; // Stores all the original validators
    function Page_ClientValidate() {
    var i;
    // Page_ValidatorAssignments gets rendered in the derived Page Class, if we have the variable on the page
    // And it is set to true then process.
    if( typeof(Page_ValidatorAssignments) != 'undefined' && Page_ValidatorAssignments == true )
    {
    // Store all the validators if not already done.
    if( Page_InitValidators == null )
    Page_InitValidators = Page_Validators;

    // Each validator assignment will render a client side array. We grab that value here
    // And assign it to the Page_Validators variable.
    Page_Validators = eval(event.srcElement.id + "Validators");

    // Loop through are new validators and evaluate them (cast them to DOM objects)
    for(i = 0; i < Page_Validators.length; i++ )
    {
    Page_Validators[i] = eval(Page_Validators[i]);
    }

    // Loop through all the InitValidators and enable/disable depending on if they are
    // Assinged to the current button or not.
    for(i = 0; i < Page_InitValidators.length; i++ )
    {
    // InArray returns -1 if the passed element is not in array, otherwise returns index of element
    if( InArray(Page_Validators, Page_InitValidators[i].id, "id") == -1 )
    {
    Page_InitValidators[i].isvalid = true;
    ValidatorEnable(Page_InitValidators[i], false);
    ValidatorUpdateDisplay(Page_InitValidators[i]);
    }
    else
    {
    ValidatorEnable(Page_InitValidators[i], true);
    }
    }

    }
    for (i = 0; i < Page_Validators.length; i++) {
    ValidatorValidate(Page_Validators[i]);
    }
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit();
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
    }

    // Returns the index of the "value" in the given array.
    // Returns -1 if not found in array.
    function InArray(array, value, attribute)
    {
    if( attribute != null )
    attribute += ".";

    for(var i = 0; i < array.length;i++)
    {
    if( eval('array[i].' + attribute + 'toString().toLowerCase()') == value.toString().toLowerCase() )
    return i;
    }
    return -1;
    }



    System.Web.UI.Page Derived Class

    1. Deriving from a .NET Class - It's simple. Just as follows.
    public class WebPage : System.Web.UI.Page


    2. ValidatorAssignments Property - This will store the validator assignments in a System.Collections.Specialized NameValueCollection object.

    public NameValueCollection ValidatorAssignments
    {
    get
    {
    return validatorAssignments;
    }
    set
    {
    validatorAssignments = value;
    }
    }
    private NameValueCollection validatorAssignments = null;


    You will need to modify the constructor of the derived WebPage class to instantiate the new property.
    		
    
    public WebPage()
    {
    validatorAssignments = new NameValueCollection();
    }


    3. Page_Load Override - We will override this method to render the client side variable needed to trigger validator assignments and the arrays that contain the button specific validator assignments.

    private void Page_Load( object sender, System.EventArgs e )
    {
    if( this.validatorAssignments != null && this.validatorAssignments.HasKeys() )
    {
    StringBuilder sb = new StringBuilder();
    sb.Append("<script>");
    sb.Append(Environment.NewLine);
    sb.Append("Page_ValidatorAssignments = true;");
    sb.Append(Environment.NewLine);
    for( int i = 0; i < this.validatorAssignments.Count; i++ )
    {
    if( this.validatorAssignments.Keys[i].ToString() != string.Empty && this.validatorAssignments[i].ToString() != string.Empty )
    {
    sb.AppendFormat(" var {0}Validators = new Array(", this.validatorAssignments.Keys[i].ToString());
    string[] keys = this.validatorAssignments[i].Split(",".ToCharArray());
    for( int k = 0; k < keys.Length; k++ )
    {
    sb.AppendFormat("'document.all[\"{0}\"]'", keys[k].Trim());
    if( k != keys.Length - 1 )
    sb.Append(",");
    }
    sb.Append(");");
    sb.Append(Environment.NewLine);

    }
    }
    sb.Append(Environment.NewLine);
    sb.Append("</script>");
    Page.RegisterClientScriptBlock("ValidatorAssignments", sb.ToString());
    }
    }


    4. Validate Override - We will first check if we have validator assignments, grab the button that was clicked from the request object and then disable all validators that are not assigned to that button.

    public override void Validate()
    {
    for( int i = 0; i < this.validatorAssignments.Count; i++ )
    {
    if( Request.Form[this.validatorAssignments.Keys[i].Replace("_", ":")] != null )
    {
    ArrayList assignedValidators = new ArrayList(this.validatorAssignments[i].Split(",".ToCharArray()));
    for( int k = 0; k < this.Validators.Count; k++ )
    {
    BaseValidator bv = (BaseValidator)this.Validators[k];
    if(!assignedValidators.Contains(bv.ClientID))
    {
    bv.Enabled = false;
    }
    }
    break;
    }
    }

    base.Validate();

    }


    Assigning Validators

    Validators are assigned at the page level in the Page_Init function. You page must be derived from your new WebPage class. You assign validators to buttons with the ValidatorAssignment.Add method. The first parameter is the button name and the second parameter is a comma delimited list of the validator ID you want to assign to the button.

    override protected void OnInit(EventArgs e)
    {
    InitializeComponent();
    this.ValidatorAssignments.Add("btnActivate", "rfvEmail,revEmail,rfvActivationCode");
    base.OnInit(e);
    }


    To assign a ValidatorAssignments from a UserControl, use the following method. This will modify the Parent page's ValidatorAssignments property (the Parent page must be derived from your new WebPage class)

    ((Test.WebControls.WebPage)this.Parent.Page).ValidatorAssignments.Add("{0}_btnLogin".Replace("{0}", this.ID), "{0}_rfvEmail,{0}_rfvPassword,{0}_revEmail".Replace("{0}", this.ID));


    That's all there is to it. If you have any questions, find bugs or have any comments please post here.

    =============================
    Complete Code
    =============================

    WebUIValidation.js

    var Page_ValidationVer = "125";
    var Page_IsValid = true;
    var Page_BlockSubmit = false;
    function ValidatorUpdateDisplay(val) {
    if (typeof(val.display) == "string") {
    if (val.display == "None") {
    return;
    }
    if (val.display == "Dynamic") {
    val.style.display = val.isvalid ? "none" : "inline";
    return;
    }
    }
    val.style.visibility = val.isvalid ? "hidden" : "visible";
    }
    function ValidatorUpdateIsValid() {
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
    if (!Page_Validators[i].isvalid) {
    Page_IsValid = false;
    return;
    }
    }
    Page_IsValid = true;
    }
    function ValidatorHookupControlID(controlID, val) {
    if (typeof(controlID) != "string") {
    return;
    }
    var ctrl = document.all[controlID];
    if (typeof(ctrl) != "undefined") {
    ValidatorHookupControl(ctrl, val);
    }
    else {
    val.isvalid = true;
    val.enabled = false;
    }
    }
    function ValidatorHookupControl(control, val) {
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
    var i;
    for (i = 0; i < control.length; i++) {
    var inner = control[i];
    if (typeof(inner.value) == "string") {
    ValidatorHookupControl(inner, val);
    }
    }
    return;
    }
    else if (control.tagName != "INPUT" && control.tagName != "TEXTAREA" && control.tagName != "SELECT") {
    var i;
    for (i = 0; i < control.children.length; i++) {
    ValidatorHookupControl(control.children[i], val);
    }
    return;
    }
    else {
    if (typeof(control.Validators) == "undefined") {
    control.Validators = new Array;
    var ev;
    if (control.type == "radio") {
    ev = control.onclick;
    } else {
    ev = control.onchange;
    }
    if (typeof(ev) == "function" ) {
    ev = ev.toString();
    ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
    }
    else {
    ev = "";
    }
    var func = new Function("ValidatorOnChange(); " + ev);
    if (control.type == "radio") {
    control.onclick = func;
    } else {
    control.onchange = func;
    }
    }
    control.Validators[control.Validators.length] = val;
    }
    }
    function ValidatorGetValue(id) {
    var control;
    control = document.all[id];
    if (typeof(control.value) == "string") {
    return control.value;
    }
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
    var j;
    for (j=0; j < control.length; j++) {
    var inner = control[j];
    if (typeof(inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
    return inner.value;
    }
    }
    }
    else {
    return ValidatorGetValueRecursive(control);
    }
    return "";
    }
    function ValidatorGetValueRecursive(control)
    {
    if (typeof(control.value) == "string" && (control.type != "radio" || control.status == true)) {
    return control.value;
    }
    var i, val;
    for (i = 0; i<control.children.length; i++) {
    val = ValidatorGetValueRecursive(control.children[i]);
    if (val != "") return val;
    }
    return "";
    }
    var Page_InitValidators; // Stores all the original validators
    function Page_ClientValidate() {
    var i;
    // Page_ValidatorAssignments gets rendered in the derived Page Class, if we have the variable on the page
    // And it is set to true then process.
    if( typeof(Page_ValidatorAssignments) != 'undefined' && Page_ValidatorAssignments == true )
    {
    // Store all the validators if not already done.
    if( Page_InitValidators == null )
    Page_InitValidators = Page_Validators;

    // Each validator assignment will render a client side array. We grab that value here
    // And assign it to the Page_Validators variable.
    Page_Validators = eval(event.srcElement.id + "Validators");

    // Loop through are new validators and evaluate them (cast them to DOM objects)
    for(i = 0; i < Page_Validators.length; i++ )
    {
    Page_Validators[i] = eval(Page_Validators[i]);
    }

    // Loop through all the InitValidators and enable/disable depending on if they are
    // Assinged to the current button or not.
    for(i = 0; i < Page_InitValidators.length; i++ )
    {
    // InArray returns -1 if the passed element is not in array, otherwise returns index of element
    if( InArray(Page_Validators, Page_InitValidators[i].id, "id") == -1 )
    {
    Page_InitValidators[i].isvalid = true;
    ValidatorEnable(Page_InitValidators[i], false);
    ValidatorUpdateDisplay(Page_InitValidators[i]);
    }
    else
    {
    ValidatorEnable(Page_InitValidators[i], true);
    }
    }

    }
    for (i = 0; i < Page_Validators.length; i++) {
    ValidatorValidate(Page_Validators[i]);
    }
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit();
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
    }
    function ValidatorCommonOnSubmit() {
    event.returnValue = !Page_BlockSubmit;
    Page_BlockSubmit = false;
    }
    function ValidatorEnable(val, enable) {
    val.enabled = (enable != false);
    ValidatorValidate(val);
    ValidatorUpdateIsValid();
    }
    function ValidatorOnChange() {
    var vals = event.srcElement.Validators;
    var i;
    for (i = 0; i < vals.length; i++) {
    ValidatorValidate(vals[i]);
    }
    ValidatorUpdateIsValid();
    }
    function ValidatorValidate(val) {
    val.isvalid = true;
    if (val.enabled != false) {
    if (typeof(val.evaluationfunction) == "function") {
    val.isvalid = val.evaluationfunction(val);
    }
    }
    ValidatorUpdateDisplay(val);
    }
    function ValidatorOnLoad() {
    if (typeof(Page_Validators) == "undefined")
    return;
    var i, val;
    for (i = 0; i < Page_Validators.length; i++) {
    val = Page_Validators[i];
    if (typeof(val.evaluationfunction) == "string") {
    eval("val.evaluationfunction = " + val.evaluationfunction + ";");
    }
    if (typeof(val.isvalid) == "string") {
    if (val.isvalid == "False") {
    val.isvalid = false;
    Page_IsValid = false;
    }
    else {
    val.isvalid = true;
    }
    } else {
    val.isvalid = true;
    }
    if (typeof(val.enabled) == "string") {
    val.enabled = (val.enabled != "False");
    }
    ValidatorHookupControlID(val.controltovalidate, val);
    ValidatorHookupControlID(val.controlhookup, val);
    }
    Page_ValidationActive = true;
    }
    function ValidatorConvert(op, dataType, val) {
    function GetFullYear(year) {
    return (year + parseInt(val.century)) - ((year < val.cutoffyear) ? 0 : 100);
    }
    var num, cleanInput, m, exp;
    if (dataType == "Integer") {
    exp = /^\s*[-\+]?\d+\s*$/;
    if (op.match(exp) == null)
    return null;
    num = parseInt(op, 10);
    return (isNaN(num) ? null : num);
    }
    else if(dataType == "Double") {
    exp = new RegExp("^\\s*([-\\+])?(\\d+)?(\\" + val.decimalchar + "(\\d+))?\\s*$");
    m = op.match(exp);
    if (m == null)
    return null;
    cleanInput = m[1] + (m[2].length>0 ? m[2] : "0") + "." + m[4];
    num = parseFloat(cleanInput);
    return (isNaN(num) ? null : num);
    }
    else if (dataType == "Currency") {
    exp = new RegExp("^\\s*([-\\+])?(((\\d+)\\" + val.groupchar + ")*)(\\d+)"
    + ((val.digits > 0) ? "(\\" + val.decimalchar + "(\\d{1," + val.digits + "}))?" : "")
    + "\\s*$");
    m = op.match(exp);
    if (m == null)
    return null;
    var intermed = m[2] + m[5] ;
    cleanInput = m[1] + intermed.replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((val.digits > 0) ? "." + m[7] : 0);
    num = parseFloat(cleanInput);
    return (isNaN(num) ? null : num);
    }
    else if (dataType == "Date") {
    var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})\\s*$");
    m = op.match(yearFirstExp);
    var day, month, year;
    if (m != null && (m[2].length == 4 || val.dateorder == "ymd")) {
    day = m[6];
    month = m[5];
    year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10))
    }
    else {
    if (val.dateorder == "ymd"){
    return null;
    }
    var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
    m = op.match(yearLastExp);
    if (m == null) {
    return null;
    }
    if (val.dateorder == "mdy") {
    day = m[3];
    month = m[1];
    }
    else {
    day = m[1];
    month = m[3];
    }
    year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10))
    }
    month -= 1;
    var date = new Date(year, month, day);
    return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
    }
    else {
    return op.toString();
    }
    }
    function ValidatorCompare(operand1, operand2, operator, val) {
    var dataType = val.type;
    var op1, op2;
    if ((op1 = ValidatorConvert(operand1, dataType, val)) == null)
    return false;
    if (operator == "DataTypeCheck")
    return true;
    if ((op2 = ValidatorConvert(operand2, dataType, val)) == null)
    return true;
    switch (operator) {
    case "NotEqual":
    return (op1 != op2);
    case "GreaterThan":
    return (op1 > op2);
    case "GreaterThanEqual":
    return (op1 >= op2);
    case "LessThan":
    return (op1 < op2);
    case "LessThanEqual":
    return (op1 <= op2);
    default:
    return (op1 == op2);
    }
    }
    function CompareValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0)
    return true;
    var compareTo = "";
    if (null == document.all[val.controltocompare]) {
    if (typeof(val.valuetocompare) == "string") {
    compareTo = val.valuetocompare;
    }
    }
    else {
    compareTo = ValidatorGetValue(val.controltocompare);
    }
    return ValidatorCompare(value, compareTo, val.operator, val);
    }
    function CustomValidatorEvaluateIsValid(val) {
    var value = "";
    if (typeof(val.controltovalidate) == "string") {
    value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0)
    return true;
    }
    var args = { Value:value, IsValid:true };
    if (typeof(val.clientvalidationfunction) == "string") {
    eval(val.clientvalidationfunction + "(val, args) ;");
    }
    return args.IsValid;
    }
    function RegularExpressionValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0)
    return true;
    var rx = new RegExp(val.validationexpression);
    var matches = rx.exec(value);
    return (matches != null && value == matches[0]);
    }
    function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
    }
    function RequiredFieldValidatorEvaluateIsValid(val) {
    return (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != ValidatorTrim(val.initialvalue))
    }
    function RangeValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0)
    return true;
    return (ValidatorCompare(value, val.minimumvalue, "GreaterThanEqual", val) &&
    ValidatorCompare(value, val.maximumvalue, "LessThanEqual", val));
    }
    function ValidationSummaryOnSubmit() {
    if (typeof(Page_ValidationSummaries) == "undefined")
    return;
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
    summary = Page_ValidationSummaries[sums];
    summary.style.display = "none";
    if (!Page_IsValid) {
    if (summary.showsummary != "False") {
    summary.style.display = "";
    if (typeof(summary.displaymode) != "string") {
    summary.displaymode = "BulletList";
    }
    switch (summary.displaymode) {
    case "List":
    headerSep = "<br>";
    first = "";
    pre = "";
    post = "<br>";
    final = "";
    break;
    case "BulletList":
    default:
    headerSep = "";
    first = "<ul>";
    pre = "<li>";
    post = "</li>";
    final = "</ul>";
    break;
    case "SingleParagraph":
    headerSep = " ";
    first = "";
    pre = "";
    post = " ";
    final = "<br>";
    break;
    }
    s = "";
    if (typeof(summary.headertext) == "string") {
    s += summary.headertext + headerSep;
    }
    s += first;
    for (i=0; i<Page_Validators.length; i++) {
    if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
    s += pre + Page_Validators[i].errormessage + post;
    }
    }
    s += final;
    summary.innerHTML = s;
    window.scrollTo(0,0);
    }
    if (summary.showmessagebox == "True") {
    s = "";
    if (typeof(summary.headertext) == "string") {
    s += summary.headertext + "<BR>";
    }
    for (i=0; i<Page_Validators.length; i++) {
    if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
    switch (summary.displaymode) {
    case "List":
    s += Page_Validators[i].errormessage + "<BR>";
    break;
    case "BulletList":
    default:
    s += " - " + Page_Validators[i].errormessage + "<BR>";
    break;
    case "SingleParagraph":
    s += Page_Validators[i].errormessage + " ";
    break;
    }
    }
    }
    span = document.createElement("SPAN");
    span.innerHTML = s;
    s = span.innerText;
    alert(s);
    }
    }
    }
    }



    System.Web.UI.Page Derived Page

    using System;
    using System.Text;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI;
    using System.Collections.Specialized;
    using System.Collections;

    namespace Test.WebControls
    {

    public class WebPage : System.Web.UI.Page
    {
    public WebPage()
    {
    validatorAssignments = new NameValueCollection();
    }

    private void Page_Load( object sender, System.EventArgs e )
    {
    if( this.validatorAssignments != null && this.validatorAssignments.HasKeys() )
    {
    StringBuilder sb = new StringBuilder();
    sb.Append("<script>");
    sb.Append(Environment.NewLine);
    sb.Append("Page_ValidatorAssignments = true;");
    sb.Append(Environment.NewLine);
    for( int i = 0; i < this.validatorAssignments.Count; i++ )
    {
    if( this.validatorAssignments.Keys[i].ToString() != string.Empty && this.validatorAssignments[i].ToString() != string.Empty )
    {
    sb.AppendFormat(" var {0}Validators = new Array(", this.validatorAssignments.Keys[i].ToString());
    string[] keys = this.validatorAssignments[i].Split(",".ToCharArray());
    for( int k = 0; k < keys.Length; k++ )
    {
    sb.AppendFormat("'document.all[\"{0}\"]'", keys[k].Trim());
    if( k != keys.Length - 1 )
    sb.Append(",");
    }
    sb.Append(");");
    sb.Append(Environment.NewLine);

    }
    }
    sb.Append(Environment.NewLine);
    sb.Append("</script>");
    Page.RegisterClientScriptBlock("ValidatorAssignments", sb.ToString());
    }
    }

    public override void Validate()
    {
    for( int i = 0; i < this.validatorAssignments.Count; i++ )
    {
    if( Request.Form[this.validatorAssignments.Keys[i].Replace("_", ":")] != null )
    {
    ArrayList assignedValidators = new ArrayList(this.validatorAssignments[i].Split(",".ToCharArray()));
    for( int k = 0; k < this.Validators.Count; k++ )
    {
    BaseValidator bv = (BaseValidator)this.Validators[k];
    if(!assignedValidators.Contains(bv.ClientID))
    {
    bv.Enabled = false;
    }
    }
    break;
    }
    }

    base.Validate();

    }

    private void InitializeComponent()
    {
    this.Load += new System.EventHandler(this.Page_Load);
    }

    protected override void OnInit(EventArgs e)
    {
    InitializeComponent();
    base.OnInit(e);
    }

    public NameValueCollection ValidatorAssignments
    {
    get
    {
    return validatorAssignments;
    }
    set
    {
    validatorAssignments = value;
    }
    }


    private NameValueCollection validatorAssignments = null;

    }
    }


    Test ASPX Page

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <title>ValidatorAssignmentTest</title>
    <script>
    // Returns the index of the "value" in the given array.
    // Returns -1 if not found in array.
    function InArray(array, value, attribute)
    {
    if( attribute != null )
    attribute += ".";

    for(var i = 0; i < array.length;i++)
    {
    if( eval('array[i].' + attribute + 'toString().toLowerCase()') == value.toString().toLowerCase() )
    return i;
    }
    return -1;
    }
    </script>
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <form id="ValidatorAssignmentTest" method="post" runat="server">
    <asp:requiredfieldvalidator id="rfv2" style="Z-INDEX: 101; LEFT: 193px; POSITION: absolute; TOP: 79px" runat="server" ControlToValidate="TextBox2" ErrorMessage="RequiredFieldValidator"></asp:requiredfieldvalidator>
    <asp:button id="Button2" style="Z-INDEX: 102; LEFT: 354px; POSITION: absolute; TOP: 79px" runat="server" Text="Submit2"></asp:button><asp:textbox id="TextBox2" style="Z-INDEX: 103; LEFT: 21px; POSITION: absolute; TOP: 79px" runat="server"></asp:textbox>
    <asp:requiredfieldvalidator id="rfv1" runat="server" ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator" style="Z-INDEX: 104; LEFT: 196px; POSITION: absolute; TOP: 40px"></asp:requiredfieldvalidator>
    <asp:textbox id="TextBox1" runat="server" style="Z-INDEX: 105; LEFT: 22px; POSITION: absolute; TOP: 33px"></asp:textbox>
    <asp:button id="Button1" runat="server" Text="Submit1" style="Z-INDEX: 106; LEFT: 355px; POSITION: absolute; TOP: 33px"></asp:button>
    </form>
    </body>
    </HTML>


    Test ASPX.CS Page


    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;

    namespace Test.TestDrivers
    {
    /// <summary>
    /// Summary description for ValidatorAssignmentTest.
    /// </summary>
    public class ValidatorAssignmentTest : Test.WebControls.WebPage
    {
    protected System.Web.UI.WebControls.RequiredFieldValidator rfv1;
    protected System.Web.UI.WebControls.Button Button1;
    protected System.Web.UI.WebControls.RequiredFieldValidator rfv2;
    protected System.Web.UI.WebControls.Button Button2;
    protected System.Web.UI.WebControls.TextBox TextBox2;
    protected System.Web.UI.WebControls.TextBox TextBox1;

    private void Page_Load(object sender, System.EventArgs e)
    {
    // Put user code to initialize the page here
    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    this.ValidatorAssignments.Add("Button1", "rfv1");
    this.ValidatorAssignments.Add("Button2", "rfv2");
    base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion
    }
    }




    Jon
  • Re: Grouping Validators by Submit Button

    08-31-2003, 6:48 AM
    • Loading...
    • jlovell
    • Joined on 07-04-2003, 1:46 PM
    • Durban, South Africa
    • Posts 134
    Absolutely brillant Jon ;) . I am just wondering, if I do this to one application and I am not going to use in other applications, would this effect the validations in the other applications. This answer will also help me decide to use it or not because I will be uploading these sites to a shared web server...

    Thanks for this post ;) .
    -- Justin Lovell
  • Re: Grouping Validators by Submit Button

    09-08-2003, 1:01 AM
    • Loading...
    • bdesmond
    • Joined on 06-15-2002, 6:02 PM
    • Chicago, IL USA
    • Posts 944
    • ControlGallery
      TrustedFriends-MVPs
    A Change to webuivalidation.js would affect the entire IIS website, as the aspnet_client is global to a website.
    --Brian Desmond
    Windows Server MVP - Directory Services
    http://www.briandesmond.com
  • Re: Grouping Validators by Submit Button

    09-08-2003, 10:21 AM
    • Loading...
    • jgallant
    • Joined on 06-27-2002, 3:22 PM
    • Posts 31
    >>if I do this to one application and I am not going to use in other applications, would this effect the validations in the other applications. This answer will also help me decide to use it or not because I will be uploading these sites to a shared web server...

    No, this will not adversly effect other applications. You will notice that in the Page_ClientValidate function I inserted this conditional statement, which will only validate to true if your page has validator assignments.


    if( typeof(Page_ValidatorAssignments) != 'undefined' && Page_ValidatorAssignments == true )

    {
  • Re: Grouping Validators by Submit Button

    09-08-2003, 10:23 AM
    • Loading...
    • jgallant
    • Joined on 06-27-2002, 3:22 PM
    • Posts 31
    >>A Change to webuivalidation.js would affect the entire IIS website, as the aspnet_client is global to a website.

    I think what you mean is that the validation file is global to all websites. You're right it is in a shared environment, but because of the check I do in the modified version of the validation file you will not have any issues.
  • Re: Grouping Validators by Submit Button

    09-08-2003, 1:39 PM
    • Loading...
    • jlovell
    • Joined on 07-04-2003, 1:46 PM
    • Durban, South Africa
    • Posts 134
    Thanks, my question was answered exactly what I wanted I wanted to know... this script will go for an awesome leep forward ;) . Again, well done and thanks for sharing this information.
    -- Justin Lovell
  • Re: Grouping Validators by Submit Button

    09-08-2003, 1:44 PM
    • Loading...
    • jgallant
    • Joined on 06-27-2002, 3:22 PM
    • Posts 31
    >Thanks, my question was answered exactly what I wanted I wanted to know... this script will go for an awesome leep forward. Again, well done and thanks for sharing this information.

    I'm glad you find this useful....it really was a major oversight by MS IMHO. Please let me know if you have issues, needed to modify the code or have ideas to make it better.

  • Re: Grouping Validators by Submit Button

    09-09-2003, 6:35 AM
    • Loading...
    • VidarMar
    • Joined on 02-19-2003, 7:52 AM
    • Posts 1
    Hi,

    I have a problem with this method.

    I have an input area with 4 textboxes, wich i have a button to submit these textboxes into the database.

    I have 4 RequiredFieldValidators on these 4 textboxes.

    Under this area I have a Repeater with 4 textboxes and a submit and a delete button.
    I dont have any validators in this repeater.

    When I hit the top submit button, the validator seem to work, but when I hit one of the buttons in the repeater, it shows me the clienside error in each Validator, at the same time i get an javascript error on the onclick funcion, saying it cannot find the function.

    Here is my code.

    aspx file
    <input class=text id=txtNewBid type=text size=10 runat="server">
    <asp:RequiredFieldValidator id=rvfNewBid runat="server" ErrorMessage="Du må legge inn bud" ControlToValidate="txtNewBid" Display="Dynamic">*</asp:RequiredFieldValidator>
    <input class=text id=txtNewEndDate type=text maxLength=8 size=8 runat="server">
    <asp:RequiredFieldValidator id=rvfNewEndDate runat="server" ErrorMessage="Du må legge inn datoen når budet går ut (dd.mm.åå)" ControlToValidate="txtNewEndDate" Display="Dynamic">*</asp:RequiredFieldValidator>
    <input class=text id=txtNewEndTime type=text maxLength=4 size=4 runat="server">
    <asp:RequiredFieldValidator id=rvfNewEndTime runat="server" ErrorMessage="Du må legge inn klokkelsettet når budet går ut (ttmm)" ControlToValidate="txtNewEndTime" Display="Dynamic">*</asp:RequiredFieldValidator>
    <input class=text id=txtNewBuyer type=text maxLength=150 size=25 runat="server">
    <asp:RequiredFieldValidator id=rvfNewBuyer runat="server" ErrorMessage="Du må legge inn budgiver" ControlToValidate="txtNewBuyer" Display="Dynamic">*</asp:RequiredFieldValidator>
    <asp:button id=btnStore runat="server" Text=" OK " BackColor="Green" CssClass="text" ForeColor="White"></asp:button>&nbsp;

    <asp:repeater id=rptrList runat="server">
    <ItemTemplate>
    <input value='<%# DataBinder.Eval(Container.DataItem, "BidKey") %>' type=hidden id=Key runat=server>
    <input type="text" value='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:#}") %>' class="text" size="10" id="txtPrice" runat="server" NAME="txtPrice">
    <input type="text" value='<%# DataBinder.Eval(Container.DataItem, "EndDate", "{0:dd.MM.yy}") %>' class="text" size="8" maxlength="8" id="txtEndDate" runat="server" NAME="txtEndDate">
    <input value='<%# DataBinder.Eval(Container.DataItem, "EndDate", "{0:hhmm}") %>' type="text" class="text" size="4" maxlength="4" runat="server" id="txtEndTime">
    <input type="text" value='<%# DataBinder.Eval(Container.DataItem, "Buyer") %>' maxlength="150" class="text" size="25" id="txtBuyer" runat="server">
    <asp:Button id="btnSaveEntry" runat="server" CommandName="UpdateEntry" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "BidKey") %>' Text=" OK " BackColor="Green" CssClass="text" ForeColor="White"></asp:Button>
    &nbsp; <asp:Button id="btnDeleteEntry" CommandName="DeleteEntry" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "BidKey") %>' runat="server" Text="Slett" BackColor="Red" CssClass="text" ForeColor="White"></asp:Button>
    </ItemTemplate>
    </asp:repeater></table><asp:ValidationSummary id=ValidationSummary1 runat="server" ShowMessageBox="True" ShowSummary="False" DisplayMode="List"></asp:ValidationSummary>



    aspx.cs file
    public class e_bid : Broker.ValidationPrButton.WebPage
    // Broker.ValidationPrButton.WebPage -- contains the code you wrote
    ...
    ...
    InitializeComponent();
    this.ValidatorAssignments.Add("btnStore", "rvfNewBid,rvfNewEndTime,rvfNewEndDate,rvfNewBuyer");
    base.OnInit(e);
    ...
    ...



    The rest of the code I have copied from you.

    Javascript Error when pressing OK button in repeater:
    rptrList__ctl0_btnSaveEntryValidators is undifined.

    Error 2:
    I get an asterix (*) i all the validators, but I don't get the validation summary.


    Please help

    Vidar M
    Norway
  • Re: Grouping Validators by Submit Button

    09-09-2003, 11:30 AM
    • Loading...
    • jgallant
    • Joined on 06-27-2002, 3:22 PM
    • Posts 31
    Set CausesValidation=false on the buttons contained within the repeater.
  • Re: Grouping Validators by Submit Button

    09-21-2003, 10:38 AM
    • Loading...
    • glsac
    • Joined on 07-26-2002, 6:57 AM
    • USA
    • Posts 6
    excellent response :) I had to do something similar a while back and I did something much easier...let me share it with you:

    Public Sub DisableValidators()
    ' Disable validation
    Dim bv As System.Web.UI.WebControls.BaseValidator
    For Each bv In Me.Validators
    bv.Enabled = False
    Next
    End Sub

    Public Sub EnableValidators()
    ' Enable validation
    Dim bv As System.Web.UI.WebControls.BaseValidator
    For Each bv In Me.Validators
    bv.Enabled = True
    Next
    End Sub


    Then in your code you basically just add the following on a submit button when needed:

    DisableValidators()
    EnableValidators()

    Now granted this is not as perfect as the solution given above simply bec. this will look at ALL validators on page and disable all of them or enable all of them. For me this worked fine because I had to some strange validation on the app...but I am sure it can be modified a bit to work for someone else :)

    Good Luck!

    -Joe
  • Re: Grouping Validators by Submit Button

    05-25-2005, 5:36 AM