I have a problem that is making me crazy. On my page I have one Javascript validation and two ASP.NET validators. The validation outcome depends just on the result of the Javascript. That means if the Javascript returns true the ASP.NET validators are not checked.
The Javascript code is:
<script type="text/javascript">
function Validate() {
var ddlObj = document.getElementById('<%=ddStatus.ClientID%>');
var txtObj = document.getElementById('<%=txtComment.ClientID%>');
if (ddlObj.selectedIndex != 0) {
if (txtObj.value == "") {
alert("Any change of Status requires a comment!");
txtObj.focus();
return false;
}
}
}
</script>
Instead the two ASP.NET validators are:
<td><asp:TextBox runat="server" ID="txtSerialNr" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="txtSerialNr" ErrorMessage="***" />
</td>
<td><asp:TextBox runat="server" ID="txtProdName" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv1" ControlToValidate="txtProdName" ErrorMessage="***"></asp:RequiredFieldValidator></td>
Anybody might help? Thanks
UPDATE:
I call the Javascript from a button:
<asp:Button runat="server" ID="btnSubmit" Text="Save New Product"
style="cursor:hand" OnClick="btnSubmit_Click" />
But I register the attribute from the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Attributes.Add("OnClientClick", "return Validate()");
}
You can fire the client side validation from within the Validate() function:
validate = function(){
bool isValid = Page_ClientValidate(""); //triggers validation
if (isValid){
var ddlObj = document.getElementById("<%=ddStatus.ClientID%>");
var txtObj = document.getElementById("<%=txtComment.ClientID%>");
if (ddlObj.selectedIndex != 0) {
if (txtObj.value == "") {
alert("Any change of Status requires a comment!");
txtObj.focus();
isValid = false;
}
}
}
return isValid;
}
Markup:
<asp:Button runat="server" OnClientClick="return validate();" ... />
OK, there's a couple of things wrong here.
If you are concerned enough to do validation, you must ALWAYS do server-side validation in addition to client-side. Client-side validation is very user-friendly and fast to respond, but it can be bypassed simply by setting JavaScript to 'off'!
I don't see where you've told your controls which JavaScript function to call when they validate? You use RequiredFieldValidators which don't require an external function - but then attempt custom validation using your Validate() function.
If you do end up using a CustomValidator, then you'll need to change the 'signature' of your function. It needs to be of the form
function validateIt(sender, args){
var testResult = //your validation test here
args.IsValid = testResult;
}
Related
I have a Telerik:RadListView control and multiple checkboxes in it. I need to validate those checkboxes before submitting the form.
I have tried build-in validators with ControlToValidate property but it gave me the error Control 'chkQuestion' referenced by the ControlToValidate property of 'chkQuestionValidator' cannot be validated. which is very logical because they are all in a RadListView.
After that, i created a CustomValidator;
<asp:CheckBox ID="chkQuestion"
CssClass="AcceptedAgreement"
Visible="true"
runat="server"
Text=" I confirm"
AutoPostBack="false" />
<asp:CustomValidator
ClientValidationFunction="CheckBoxRequired_ClientValidate"
EnableClientScript="true"
ID="chkQuestionValidator"
runat="server"
Enabled="true"
SetFocusOnError="true"
ErrorMessage="Please confirm"
ForeColor="Red" />
these are all in Telerik:RadListView which means i have multiple of them but i cant link them in my client-side custom validator function.
Here is my validator function:
function CheckBoxRequired_ClientValidate(sender, e) {
var c = jQuery(".AcceptedAgreement input:checkbox");
var chb = validator
if (c.is(':checked')) {
e.IsValid = true;
} else {
e.IsValid = false;
}
}
but with this function i cant validate them seperately. when one of the checkboxes checked, this function act like all of them are checked. this is because they all have same css class, and this is the point i stucked.
if you help me, it will be appreciated.
For those who come here for solution, here it is:
function handleSubmitForm(sender, args) {
var c = jQuery(".AcceptedAgreement input:checkbox");
c.each(function (index) {
if (!c[index].checked) {
args.set_cancel(true);
}
});
args.set_cancel(true);
}
basically i assign this piece of code to my button, it is called before doing postback, and if it does not fit my condition, it stops the postback. you can do whatever you want in if clause.
you can call this function :
<telerik:RadButton ID="btnSubmit"
OnClientClicking="handleSubmitForm"
Text="Submit" OnClick="btnSubmit_Click" />
I have four text boxes in 4 different tabs of an ASP.NET Page. I need to provide same validation message to all the text boxes. Presently I am using four different functions with same functionality. Kindly suggest a way to identify which textbox is being used make that a single funtion
Code from Commend:
<asp:TextBox ID="textBox1" runat="server" ValidationonGroup="abcd"></asp:TextBox>
<asp:CustomValidator ID="ID1" runat="server" ValidationGroup="abcd"
ControlToValidate="textBox1" ErrorMessage="message"
ClientValidationFunction="fname"></asp:CustomValidator>
--Javascript Fn--
function fname(sender, args) {
var x = document.getElementById('<%=txtBox1.ClientID%>').value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Edit
if you are using Asp.Net then you should use like this
Aspx page code
<div>
<asp:TextBox runat="server" ID="txt1" ClientIDMode="Static" onKeyPress="javascript:text_changed(this.id);"></asp:TextBox>
</div>
JS Code
<script type="text/javascript">
function text_changed(event)
{
var id = event;
alert(id);
}
</script>
You got the textbox id in id variable and now u can get value etc using this id you are applying your conditions.... i hope this will help u
I have a button with OnClick event on my web page.
<asp:TextBox ID="tbMailID" runat="server" Width="250px"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
C# code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
bool IsGmail = CheckMailId(tbMailID.Text);
if(!IsGmail)
{
string strScript = "confirm('Mail id is not from gmail, do you still want to continue?');";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", strScript, true);
}
SendMail();
}
The page accepts a mail id in textbox and on submit sends a mail.
But if mail-id is not an gmail id (validated by CheckMailId) i want to show a confirmation box to user whether he/she wants to get a mail, based on the Yes/No clicked.
But the javascript will get call after the submit event is served and mail is sent.
if i add a return SendMail() will never get calls
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", strScript, true);
return;
What could be a possible solution here?
Note: the code posted is simplified version of my real use case.
CheckMailId - is just a name to show, it calls up many other functions and do few db process. So incorporating that in javascript, i would like to avoid.
You can call a script befroe event lke this:-
<script type="text/javascript">
function Confirm() {
var yourstring = document.getElementById('<%= tbMailID.ClientID %>').value;
if (/#gmail\.com$/.test(yourstring)) {
return true;
}
else
{
if (confirm("Mail id is not from gmail, do you still want to continue?") == true)
return true;
else
return false;
}
}
</script>
strong text
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return Confirm();" OnClick="btnSubmit_Click" Text="Submit" />
I have some javascript that "freezes" the screen when a submit button is pressed. This is to stop double clickers.
I have discovered that there is an issue if a validator control returns false, in that, the screen has "frozen", so the user can't fix the problem with their input data.
I need to be able to tell if the page is valid or not, so that if it is not, i can un-freeze the screen.
How can I do this??
javascript code that freezes the screen... (originally from 4guysfromrolla)
function FreezeScreen(msg) {
var outerPane = document.getElementById('FreezePane');
var innerPane = document.getElementById('InnerFreezePane');
if (outerPane) outerPane.className = 'FreezePaneOn';
}
code that runs the javascript...
<asp:Button ID="btnSubmit" runat="server" Text="<%$ Resources:LocalizedText, button_SubmitOrder %>" onclick="btnSubmit_Click" ValidationGroup="validateHeader" OnClientClick="FreezeScreen();" />
It will probably be something like this.
function ValidatePage() {
FreezeScreen();
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
UnFreezeScreen();
return true;
}
else {
UnFreezeScreen();
return false;
}
}
And on the button
<asp:Button ID="btnSubmit" runat="server" Text="<%$ Resources:LocalizedText, button_SubmitOrder %>" onclick="btnSubmit_Click" ValidationGroup="validateHeader" OnClientClick="return ValidatePage();" />
I have validation controls in my page and I am using Validation summary message box to display the validation messages,the javascript function shown below worked for me but the problem is I am using this javascript function on OnClientClick event of the button and when I click the button with form controls not been filled its displaying the validation summary message box as expected but when i close the summary box it's getting displayed again and i need to close the message box to disappear, means i have to do two clicks everytime. Can somebody correct me what am I doing wrong.
Here is what I am doing:-
<asp:Button ID="SubmitButtonOne" runat="server" Text="Submit" OnClick="SubmitButtonOne_Click"
ValidationGroup="Cases" ClientIDMode="Static" OnClientClick="PleaseWaitShow()" />
Here is the javascript function:
function PleaseWaitShow() {
var isPageValid = true;
// Do nothing if client validation is not active
if (typeof (Page_Validators) != "undefined") {
if (typeof (Page_ClientValidate) == 'function') {
isPageValid = Page_ClientValidate();
}
}
if (isPageValid) {
document.getElementById('SubmitButtonOne').value = "Processing...";
}
}
code behind:
protected void SubmitButtonOne_Click(object sender, EventArgs e)
{
try
{
// some functionality
}
catch (Exception)
{
//show errror message
}
}
It is expected behavior.
Once Page_ClientValidate is fired due to your explicit call inside PleaseWaitShow method and second is an implicit call made by the PostBack button click.
And so you are seeing two times the ValidationSummary message box.
I don't have a solution to circumvent this but will update if something strikes.
Note: One thing I would like to point out is since you have ValidationGroup="Cases" on your submit button you should pass that to your Page_ClientValidate method.
Update 1: One way I can think of is trying something like this:
1: OnClientClick="return PleaseWaitShow();"
2: return isPageValid from PleaseWaitShow():
function PleaseWaitShow() {
var isPageValid = true;
....
....
....
return isPageValid;
}
No, it is not the expected behavior. Rather, it's a bug in ASP.NET validation JS code.
The ValidationSummaryOnSubmit function loops over all summaries, and for each summary, loops over all validators. If not group is specified, then each validator's message is appended, resulting in 2 (3, 4, 5?) repetitions of the same messages.
I solved the problem by fixing the function (staring at line 53 or so):
....
for (i = 0; i < Page_Validators.length; i++)
{
var validator = Page_Validators[i];
if (validator.validationGroup != null && summary.validationGroup != null)
{
if (validator.validationGroup != summary.validationGroup) continue;
}
if (!validator.isvalid && typeof (validator.errormessage) == "string")
{
s += pre + validator.errormessage + post;
}
}
....
if you use Page_ClientValidate method, you should set causevalidation to false. CausesValidation="false"
because Page_ClientValidate is already doing this for button or control you validate
Please remove ValidationGroup of Button. Only user for ValidationSummary
Like:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqvName" runat="server" ControlToValidate="txtName" ErrorMessage="Please enter Name" ValidationGroup="SaveName"> </asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" OnClientClick="DisableButton();" Text="Save this Name" ></asp:Button>
<asp:ValidationSummary ID="valSaveName" runat="server" ValidationGroup="SaveName" ShowMessageBox="true" ShowSummary="false" />
Thanks