2011-12-20 36 views
0

我想在運行時將一個必需的字段驗證器添加到我的頁面。 沒什麼特別的有:動態創建requiredfieldvalidator繞過客戶端驗證

<form id="form1" runat="server"> 
<asp:ScriptManager ID="ScriptManager1" runat="server"> 
</asp:ScriptManager> 
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
     <asp:Button ID="Button1" runat="server" Text="Button" /> 
     <asp:ValidationSummary ID="ValidationSummary1" 
     runat="server" ShowMessageBox="True" ShowSummary="False" /> 
</form> 

和@代碼隱藏

protected void Page_Init(object sender, EventArgs e) 
    { 
     RequiredFieldValidator theValid = new RequiredFieldValidator(); 
     theValid.ID = "0000" + "RFV"; 
     theValid.ControlToValidate = TextBox1.ID; 
     theValid.ErrorMessage = "Message here" 
     theValid.Text = "*"; 
     theValid.Display = ValidatorDisplay.Dynamic; 
     theValid.EnableClientScript = true; 
     theValid.EnableViewState = true; 
     theValid.SetFocusOnError = true; 
     theValid.Enabled = true; 
     theValid.Visible = true; 
     Page.Validators.Add(theValid); 
     form1.Controls.Add(theValid); 
    } 

當我點擊它只是驗證服務器端的按鈕,而不是客戶端。我錯過了什麼?

TIA。

回答

0

你可以用jquery檢查你的代碼。

function TextBoxValidate() { 
$('input:[type="text"]:[id*="TextBox1"]').each(function() { var txtId = this.id; $('span').each(function() { if (this.controltovalidate == txtId) ValidatorValidate(this); }); }); 
} 
function InitValidationOnClick() 
{ 
$('input:[id*="Button1"]').each(function(){$(this).on('click', function(){TextBoxValidate(); return Page_IsValid;});}); 
// or other case 
//$('form:[id*="form1"]').each(function(){$(this).on('submit', function(){TextBoxValidate(); return Page_IsValid;});}); 
} 
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitValidationOnClick); 

如果驗證器存在於頁面中,它將在點擊(提交)事件客戶端驗證。

0

您好所有嘗試隨着RequiredField驗證

代碼這一個單選按鈕

TableRow trow4 = new TableRow(); 
    trow4.Style.Add("width", "100px"); 
    TableCell tcel4 = new TableCell(); 
    Label lb4 = new Label(); 
    lb4.Text = Resources.QcLabelName.Gender; 
    tcel4.Controls.Add(lb4); 
    CSSCell(tcel4); 
    table.Rows.Add(trow4); 
    RadioButtonList rblist = new RadioButtonList(); 
    rblist.ID = "rbtnmalendfemale"; 
    rblist.Items.Add("Male"); 
    rblist.Items.Add("Female"); 
    tcel4.Controls.Add(rblist); 
    trow4.Cells.Add(tcel4); 
    table.Rows.Add(trow4); 
    rblist.Visible = true; 
    RequiredFieldValidator rFV5 = new RequiredFieldValidator(); 
    TableCell tcl46 = new TableCell(); 
    rFV5.ControlToValidate = "rbtnmalendfemale"; 
    rFV5.ErrorMessage = "Gendor Selection Is Mandatory"; 
    rFV5.Style.Add("color", "Red"); 
    rFV5.ID = "Reqfield9"; 
    tcl46.Controls.Add(rFV5); 
    trow4.Cells.Add(tcl46); 
    table.Rows.Add(trow4); 
    rFV5.Visible = true;******