When I click the asp.net button as per the below code, it goes into my js file, and gets the function as I need, however if it fails validation it still goes through with the postback as if it were valid.
the asp.net button
<asp:Button ID="bttnSend" runat="server" OnClientClick="DoValidation()" Text="Send" CssClass="btn btn-primary margin30" />
the javascript
function DoValidation(parameter) {
console.log("validating");
var valid = true;
var emailTo = document.getElementById("txtEmailTo").value;
if (emailTo.length < 1) {
alert("Please select at least one recipient to send an email to");
valid = false;
}
console.log(valid);
if (valid == true) {
__doPostBack('bttnSend', parameter);
}
};
I would be grateful if someone could please tell me what i need to change and what to so that the validation doesnt allow the postback if it fails.
thanks
You need to prevent the default action of button when condition fails.
Modify your function to return true/false
function DoValidation(parameter) {
var valid = true;
var emailTo = document.getElementById("txtEmailTo").value;
if (emailTo.length < 1) {
alert("Please select at least one recipient to send an email to");
valid = false;
}
return valid;
};
The use the return value
<asp:Button ID="bttnSend" runat="server" OnClientClick="return DoValidation()" Text="Send" CssClass="btn btn-primary margin30" />
Related
I am working on a web forms project. I have many phone number fields. I have added both a RequiredFieldValidator and a RegularExpressionValidator to each phone field as well as a PhoneNumberFormatter() javascript function to the oninput event for each asp:Textbox.
The main way to express my problem is that the RegualrExpressionValidator will still allow the asp:Button to submit the page even when there is an incomplete phone number in those boxes.
I have added a DoPost() function to the buttons OnClientClick event that cycles through all the validators and turns all the inputs red that have not met their validator's parameters. But still the RegularExpressionValidator is still allowing incomplete phone numbers to pass through when the button is pressed.
The only way that I have found to overcome this is by adding a function to agressively validate the phone length as needed, and use the setCustomValidity javascript function, which works to keep the page from submitting with incomplete numbers, but for some reason that undoes all the other boxes that I turned red for not passing their validation.
For some reason, if I click submit twice, THEN the boxes that are supposed to turn red will finally turn red. This was not a problem until I added the setCustomValidity to the phone inputs that were incomplete, otherwise the fields would turn red when expected on the first click, BUT incomplete partial phone numbers were passing through.
Basically, I want to know what I can do with basic validators and javascript to ensure the phone number is the length I need and wont interfere with the other function of turning the other required fields red when they need to.
Markup for phone input
<div class="form-group">
<label>School Contact Administrator Phone:</label>
<asp:TextBox runat="server" ID="MainContactPhone" CssClass="form-control" TextMode="Phone"
oninput="PhoneNumberFormatter(ContentPlaceHolder1_MainContactPhone); ReValidateText(ContentPlaceHolder1_MainContactPhone)"/>
<asp:RegularExpressionValidator ID="MainContactRegVal" runat="server" CssClass="text-danger"
ErrorMessage="Not a valid phone number" ControlToValidate="MainContactPhone"
ValidationExpression="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$" />
<asp:RequiredFieldValidator runat="server" ValidationGroup="ValGro" ID="MainContactVal"
ControlToValidate="MainContactPhone" InitialValue=""
Text="Required Field" CssClass="text-danger" />
</div>
Markup for Submit Button
<asp:Button runat="server" ID="IntakeTypeSubmit" Text="Next"
OnClick="IntakeTypeSubmit_Click"
CssClass="btn btn-info" ValidationGroup="ValGro" OnClientClick="DoPostIntro()" />
JS for DoPostIntro()
function DoPostIntro() {
try {
//DoPost(); //I have tried changing the order of when I do the base DoPost()
var phone = document.getElementById('ContentPlaceHolder1_MainContactPhone');
var reqVal = document.getElementById('ContentPlaceHolder1_MainContactVal');
var regVal = document.getElementById('ContentPlaceHolder1_MainContactRegVal');
ValidatePhone(phone, reqVal, regVal);
DoPost();
} catch (Error) {
alert(Error);
}
}
JS for base DoPost()
function DoPost() {
try {
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var ctrl = document.getElementById(val.controltovalidate);
if (ctrl != null && ctrl.style != null) {
if (!val.isvalid) {
ctrl.style.backgroundColor = '#FFAAAA';
}
else {
ctrl.style.backgroundColor = '';
}
}
}
document.getElementById('Warning').style.visibility = 'visible';
} catch (Error) {
alert(Error);
}
}
JS for ValidatePhone
function ValidatePhone(input, reqVal, regVal) {
if (input.value == '' && (reqVal.enabled == true || reqVal.enabled === undefined)) {
input.style.backgroundColor = '#FFAAAA';
ValidatorEnable(reqVal, true);
reqVal.style.visibility = 'visible';
}
if (input.value.length < 14 && (regVal.enabled == true || regVal.enabled === undefined)) {
input.style.backgroundColor = '#FFAAAA';
ValidatorEnable(regVal, true);
input.setCustomValidity("Invalid Phone Number");
regVal.style.visibility = 'visible';
} else {
input.setCustomValidity("");
regVal.style.visibility = 'hidden';
}
}
C# that registers the DoPostIntro()
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "DoPostIntro();");
I'm trying to validate the TextBox and click the Button of asp.net.
<asp:TextBox ID="txtEmail" Placeholder="E-mail" runat="server"></asp:TextBox>
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" />
And here is a jQuery code which validate TextBox and then trigger the OnClick method:
var al = document.getElementById('<%=lblAlert.ClientID%>');
var email = document.getElementById('<%=txtEmail.ClientID%>');
var msg = null;
$(document).ready(function () {
$('#<%=btnLogin.ClientID%>').on('click', function (e) {
if (email.innerText == '') {
msg = 'Please! enter email address.';
al.innerText = msg;
}
else {
$('#<%=btnLogin.ClientID%>').click();
}
});
});
Edit:
OnClick method is:
protected void btnLogin_Click(object sender, EventArgs e)
{
// some code
}
You should cancel the click event, when needed, using event.preventDefault().
$(document).ready(function () {
$('#<%=btnLogin.ClientID%>').on('click', function (e) {
if (email.innerText == '') {
msg = 'Please! enter email address.';
al.innerText = msg;
e.preventDefault();
}
});
});
No need to call click again if validation succeeds.
Since in the HTML your button is already clicked when the jquery gets called, your
else {
$('#<%=btnLogin.ClientID%>').click();
}
is redundant.
Here is the thing, if you want to validate and then click, then you should use a different element as a button
If you want to use the same button (recommended) then you have to prevent the postback when the validation fails by returning false.
Simple HTML concepts
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" OnClientClick="return false;" />
Will never cause a postback
Here is what I would do
<asp:TextBox ID="txtEmail" Placeholder="E-mail" runat="server"></asp:TextBox>
<asp:Button ID="btnLogin" OnClick="btnLogin_Click" runat="server" Text="Login" OnClientClick="ValidateMe()" />
<script>
var al = document.getElementById('<%=lblAlert.ClientID%>');
var msg = null;
function ValidateMe() {
var email = document.getElementById('<%=txtEmail.ClientID%>');
if (email.innerText == '') {
msg = 'Please! enter email address.';
al.innerText = msg;
return false;
}
else {
return true;
}
}
</script>
I have a modalpopupextender with a targetcontrolid = buttCopyFormula. The buttCopyFormula is wrapped in a span tag for the user to verify they want to proceed. The button also has a javascript function that verifies there is text in one of the fields and if there is places it in a textbox within the modalpopup.
If there isn't text in the field I want to cancel the popup and display a message.
I've had the span around the button for a while, but am just adding the verification function. I would imagine there is a better way to do this, but just not sure what it is.
What is the best way to execute this functionality?
TargetControl Button
<span onclick="return confirm('Copy the selected formula?')">
<asp:ImageButton ID="buttCopyFormula" ImageAlign="AbsBottom" OnClientClick="transferName()" runat="server" ImageUrl="~/images2020/copy_32.png" />
<b style="color:White">Copy</b>
</span>
Modal Popup
<asp:ModalPopupExtender ID="ModalPopupExtender2" Y="20" runat="server"
BackgroundCssClass="modalBackground" CancelControlID="buttFormulaCancel"
PopupControlID="Panel2" TargetControlID="buttCopyFormula">
</asp:ModalPopupExtender>
<asp:Panel ID="Panel2" runat="server" CssClass="modalQuestionBackground"
Style="display:none"><br />
<h5>Enter a Name for the Formula</h5>
<br /><br />
Formula Name:
<asp:TextBox ID="txtFormulaNameNew" CssClass="controltext" Width="65%" runat="server" Text=""></asp:TextBox><br /><br />
<center>
<asp:Button ID="buttFormulaSaveNew" runat="server" CssClass="button"
OnClick="buttFormulaSaveNew_Click" Text="Save Formula" />
<asp:Button ID="buttFormulaCancel" runat="server" CssClass="button"
Text="Cancel" />
</center>
<br />
</asp:Panel>
JavaScript Function
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (v === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
}
f.value = v
}
I've been working on this and first removed the span around the button, put a fake hyperlink for the modal popup and added a behavior id to the popup. I have also changed the javascript as follows...
New Javascript
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (f === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
} else {
if (confirm('Copy selected formula?')) {
f.value = v;
var mod = $find("ModalPopupExtender2");
alert(mod.id.toString);
mod.show;
return false;}
}
}
I still can't get the modalpopup to show. I imagine it's because it's wrapped in an update panel. Any ideas??
You may subscribe to showing event of ModelPopupExtender and cancel showing dependent on some conditions. Put script below at page AFTER THE ScriptManager control
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
function pageLoadedHandler(sender, args){
var popupExtender = $find("ModalPopupExtender2"); // BehaviorId of popup extender
popupExtender.remove_showing(onPopupShowing);
popupExtender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var txtFormulaNameNew;
var txtFormulaName = $get("<%= txtFormulaName.ClientID %>");
if (formulaTextBox.value.length === 0) {
alert("Please select the formula you want to copy before proceeding");
args.set_cancel(true);
} else {
if (confirm('Copy selected formula?')) {
txtFormulaNameNew = $get("<%= txtFormulaNameNew.ClientID %>");
txtFormulaNameNew.value = txtFormulaName.value;
}
}
}
I have 2 ASPxTextBox, ASPxValidationSummary and ASPxButton
In JS file there is OnPasswordValidation function
But when i type a password then click Tab button the SetIsValid(false)
on txt_password control doesn't work but it work on txt_ConfirmPassword
Why ?
<dx:ASPxTextBox ID="txt_password" runat="server" Password="true" AssociatedControlID="txt_password">
<ClientSideEvents Validation="OnPasswordValidation" />
</dx:ASPxTextBox>
<dx:ASPxTextBox ID="txt_ConfirmPassword" runat="server" Password="true" AssociatedControlID="txt_ConfirmPassword">
<ClientSideEvents Validation="OnPasswordValidation" />
</dx:ASPxTextBox>
<dx:ASPxButton ID="btnSubmit" runat="server" Text="Submit" ClientInstanceName="btnSubmit" onclick="btnSubmit_Click" AutoPostBack="False">
<ClientSideEvents Click="function(s, e) {onClickBtnSubmit();}"/>
</dx:ASPxButton>
function OnPasswordValidation(s, e) {
var objpassword = GetObj('txt_password');
var objConfirmPassword = GetObj('txt_ConfirmPassword');
var password = aspxGetControlCollection().Get(objpassword.id);
var ConfirmPassword = aspxGetControlCollection().Get(objConfirmPassword.id);
if (password.GetValue() == null) {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
return;
}
if (ConfirmPassword.GetValue() == null) {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
return;
}
if (password.GetValue().length > 5 || ConfirmPassword.GetValue().length > 5) {
if (password.GetValue() == ConfirmPassword.GetValue()) {
password.SetIsValid(true);
ConfirmPassword.SetIsValid(true);
}
else {
password.SetIsValid(false);
ConfirmPassword.SetIsValid(false);
password.SetErrorText = "Password must equal with Confirm Password";
ConfirmPassword.SetErrorText = "Password must equal with Confirm Password";
}
}
else {
ConfirmPassword.SetIsValid(false);
password.SetIsValid(false);
}
}
This is not a proper way to implement validation. This way OnPasswordValidation function is executed twice, once for every textbox.
Here is a ticket with sample project that should do what you need:
http://www.devexpress.com/Support/Center/p/Q233058.aspx
I advice you to read DevExpress controls validation overview in order to understand how to implement validation on devex controls.
I m calling a javascript function on asp.net button client click and want to prevent post back. function works but it do not stop to be posted back. My Javascript is:
function User2Check()
{
var user2id=document .getElementById("txtP2UserName");
var user2password=document .getElementById("txtP2Password");
if(user2id.value=='' & user2password.value!='')
{
alert("User name is required");
user2id=document .getElementById("txtP2UserName").foucs();
e.preventDefault();
return false;
}
if(user2id.value!='' & user2password.value=='')
{
alert("Password is required");
user2id=document .getElementById("txtP2UserPassword").foucs();
e.preventDefault();
return false;
}
}
The I am calling this function is:
<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check();" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />
plz guide.
Your javascript takes a parameter but the call from the button's OnClientClick has no parameter. I would think since e is null, the function terminates or returns before returning false but since focus() calls are before calling anything on e, the function seems to be working.
you should use && instead of &
if(user2id.value!='' && user2password.value=='')
AND : Function needs an argument, but you are calling with no argument
You can do it as
function User2Check(e)
{
var user2id=document .getElementById("txtP2UserName");
var user2password=document .getElementById("txtP2Password");
if(user2id.value=='')
{
alert("User name is required");
user2id=document .getElementById("txtP2UserName").focus();
e.preventDefault();
return false;
}
if(user2password.value=='')
{
alert("Password is required");
user2id=document .getElementById("txtP2UserPassword").focus();
e.preventDefault();
return false;
}
return true;
}
<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check(event);" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />
You use below code and remove " e.preventDefault();" from code.
function User2Check()
{
var user2id=document .getElementById("txtP2UserName");
var user2password=document .getElementById("txtP2Password");
if(user2id.value=='')
{
alert("User name is required");
user2id=document .getElementById("txtP2UserName").focus();
return false;
}
if(user2password.value=='')
{
alert("Password is required");
user2id=document .getElementById("txtP2UserPassword").focus();
return false;
}
return true;
}
and in server side code
use
<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check();" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />
You've misspelled foucs();
The code will stop running after that error.
Since you don't appear to be returning true, put an exclamation mark before the function. For example:
!function(){
// Code here!
}