The email id is entered into a textbox and the validation for email is applied but there seems to be an error that the whole function is probably not called during execution
<head runat="server">
<title></title>
<script type="text/javascript">
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.Text %>');<!--textbox4 is used to receive the email entered by the user-->
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (textbox.value.length > 0)<!--the email field should be non empty-->
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");<!--incase of an invalid email-->
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" style="margin-left: 340px" Text="Submit" Width="96px" OnClick="Button1_Click1" OnClientClick="javascript:IsValidUrl();"/>
</form>
</body>``
There seems couple of issue with the javascript's IsValidURL function so please replace it with below code.
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.ID %>');
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (emailbox.value.length > 0)
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
There are mainly two problems
<%=TextBox4.Text %> here you want id of the textBox but you are fetching value of the textBox.
textbox.value.length you want to check value of the TextBox4 but its variable name is emailbox, not textbox.
So I have just corrected those.
Hope this helps you.
Probably your function is working correctly but the page gets submitted even after the validation so replace below:
OnClientClick="javascript:IsValidUrl();"
with
OnClientClick="return javascript:IsValidUrl();"
Edit
Just figured an error in your JS code if (textbox.value.length > 0) line should be if (emailbox.value.length > 0) so try with replace it.
Another issue I found in document.getElementById('<%=TextBox4.Text %>') which should be document.getElementById('<%=TextBox4.ID %>') and in case of using master pages it should be document.getElementById('<%=TextBox4.ClientID %>') so try replacing it too.
Hope this will help !!
Related
I am developing asp.net application, in that i have a page contains gridview with text boxes,
in that i need to validate to fill atleast one text box in that gridview.
I googled many pages, but i have found only check box validation like this,
when save button click, i need to validate to fill atleast one text box in deposit amount in that gridview..
please any answers would be appreciated..
Use RequiredFieldValidator
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtAmount" ErrorMessage="Fill This"></asp:RequiredFieldValidator>
<script type="text/javascript">
function validateTextBox() {
//get target base & child control.
var TargetBaseControl = document.getElementById('<%=this.Gridview1.ClientID%>');
var TargetChildControl1 = "txtDepositAmount";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'text' && Inputs[n].id.indexOf(TargetChildControl1, 0) >= 0)
if (Inputs[n].value != "") return true;
alert('Enter Atleast One Deposit Amount!');
return false;
}
</script>
<asp:ImageButton ID="btnSave" runat="server" ValidationGroup="valInsert" ImageUrl="~/images/save6.png"
Width="40px" Height="40px" OnClientClick="javascript:return validateTextBox();" OnClick="btnSave_Click" ToolTip="Save" />
You can use a CustomValidator and jQuery to check if at least one TextBox has text in it.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="At least one TextBox is required" ClientValidationFunction="validateMyTextBoxes"></asp:CustomValidator>
<script type="text/javascript">
function validateMyTextBoxes(oSrc, args) {
var isValid = false;
$("#<%= GridView1.ClientID %> input[type=text]").each(function () {
if ($(this).val() != "") {
isValid = true;
}
})
args.IsValid = isValid;
}
</script>
I am using this to check if fields are empty. The problem is, the error message is never thrown when a field is empty, it allows submission. Is it because I am trying to run onclick and onclientclick on the button? This is my syntax
HTML
<asp:Button ID="main1212" runat="server" Text="Check If JS Works"
OnClick="DoSomethingDoNothing_OnClick" OnClientClick="return ValidateData();" />
JS
<script type="text/javascript">
function ValidateData() {
var main1212, dropdownselection, dropdownselection1, field21
main1212 = document.getElementByID("txt313").value;
dropdownselection = document.getElementByID("dropdownlist1").value;
dropdownselection1 = document.getElementByID("dropdownlist11").value;
field21 = document.getElementByID("txt12").value;
if (main1212 == '')
{
alert("Error");
return false;
}
if (dropdownselection == '')
{
alert("Error");
return false;
}
if (dropdownlist1 == '')
{
alert("Error")
return false;
}
if (field21 == '')
{
alert("Error");
return false;
}}
</script>
EDIT
If I open the browser console and press the button that should run my script their are no errors displayed?
It's missing a semi-colon in this line (not sure) of the function ValidateData:
var main1212,dropdownselection,dropdownselection1,field21;
(it's good to avoid extra spaces and also not create variables for this)
And it could be more simple, or like this:
window.onload=function(){document.getElementById('main1212').onclick=function(){ValidateData();};}
I have a texbox that is like this:
<input type="text" size="30" name="form[id]" id="form_id">
I need a JavaScript function that will validate:
No Spaces allowed.
Only numbers, letters, dashes(-) and underscores(_) allowed and no other special character allowed.
Shouldn't be empty
On Submit when the user's input is violating a validation. An alert message should be displayed.
With jQuery I'll do something like that :
$('#formId').submit(function(e) {
var validator = new RegExp(/^[\w_-]{1,}$/), //Min 1 char or more
text = $('input[name="form[id]"]').val();
if(validator.test(text))
$(this).submit();
else {
alert('Code not valid');
return false;
}
});
Regular Expressions Cheat Sheet
NB : jsfiddle is down atm, code hasn't been tested
Here is the javascript
<script type="text/javascript">
function NoSpecialChars(){
var element=document.getElementById('form_id');
var specialchars= "!##$%^&*()+=[]\\\';,./{}|\":<>?";
if(element.value.length==0){
alert('Enter some text');
return false;
}
for (var i = 0; i < element.value.length; i++) {
if (specialchars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Those are not allowed.");
return false;
}
}
return true;
}
</script>
You need to subscribe the onclientclick event of the textbox.
<input type="text" size="30" name="form[id]" id="form_id" onclientclick="return NoSpecialChars();">
Hope it helps
Use JQuery Validation Engine for Validating the Form..
Here is the Link for JQuery Validation
I am validating a form from javascript.
The target is: if user do not enter value in a required field, an error message will show up and will disappear after few seconds.
BUT
The problem is: The error message don't show up and this is probably because from javascript I am failing to write error message in a label control. BUT, if I use javascript alert instead of displaying the label, it works.
The code:
Javascript
<script type="text/javascript">
function showConfirmation() {
$('div#confirmationDV').show();
setTimeout(function () {
$('div#confirmationDV').fadeOut(5000);
});
}
function validateRequiredField() {
if (document.getElementById("<%=txtOfferTitle.ClientID%>").value == "") {
alert("error.....");//this alert works.
document.all("<%=lblConfirmation.ClientID%>").innerHTML = "please enter your business name"; // this does not work
document.all("<%=lblConfirmation.ClientID%>").style.color = "red";
showConfirmation();
document.getElementById("<%=txtOfferTitle.ClientID%>").focus();
return false;
}
return true;
}
</script>
HTML
<div class="round-conf-box" id="confirmationDV">
<div class="round-conf-tl">
<div class="round-conf-tr"></div>
<div class="round-conf-background_color_top"></div>
</div>
<div class="round-conf-box-Content">
<asp:Label ID="lblConfirmation" runat="server" CssClass="confirmationLabel"></asp:Label>
</div>
<div class="round-conf-bl">
<div class="round-conf-br"></div>
<div class="round-conf-background_color_bottom"></div>
</div>
//...some other stuff
<asp:ImageButton ID="iBtnSave" runat="server" ImageUrl="~/images/createOffer.png"
onclick="iBtnSave_Click" OnClientClick="return validateRequiredField()" />
and in the code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
iBtnSave.Attributes.Add("onclick", "return validateRequiredField()");
//some other stuff
}}
Would be nice if anyone can help me to find my mistakes..
cheers
You mix jQuery and IE-Only JScript.
Make sure to only use jQuery or cross browser JavaScript
Change
function validateRequiredField() {
if (document.getElementById("<%=txtOfferTitle.ClientID%>").value == "") {
alert("error.....");
document.all("<%=lblConfirmation.ClientID%>").innerHTML = "please enter your business name";
document.all("<%=lblConfirmation.ClientID%>").style.color = "red";
showConfirmation();
document.getElementById("<%=txtOfferTitle.ClientID%>").focus();
return false;
}
return true;
}
to
$("#<%=iBtnSave.ClientID%>).click(function(e) {
var txtOffer = $("#<%=txtOfferTitle.ClientID%>");
var txtOfferLbl = $("#<%=lblConfirmation.ClientID%>");
if (txtOffer.val() == "") {
alert("error.....");
txtOfferLbl.text("please enter your business name");
txtOfferLbl.addClass("error");
showConfirmation();
txtOffer.focus();
e.preventDefault();
}
else {
txtOfferLbl.text("");
txtOfferLbl.removeClass("error");
}
});
I have a html input button like this
<input type="button" id="send_button" class="form_button" value="Send" onclick="return validateTextBoxes();" runat="server" />
And also I have javascript
<script language="javascript">
function validateTextBoxes()
{
var reading1 = document.getElementById('<%= meterReading1.ClientID%>').value;
var error = document.getElementById('<%= lblError.ClientID%>');
var btn = document.getElementById('<%= send_button.ClientID%>');
var ValidationExpression = /[\d]/;
if (reading1 == "" )
{
error.innerHTML = "Please enter Water Meter Reading.";
return false;
}
else if(!ValidationExpression.test(reading1)) {
error.innerHTML = "Please enter valid Meter Reading(It Contains only numbers)";
return false;
}
else
{
error.innerHTML = "";
return true;
}
}
</script>
And I am also calling this server click event in the code behind file
this.send_button.ServerClick += new System.EventHandler(this.send_ok);
So here is the problem when javscript returns true its not firing the serverclick event.
Please help me where I am doing wrong(I am using framework 1.1)
Thanks
I had this problem once and I actually had to do something like this:
onclick="if (validateTextBoxes()) { return true; } else { return false; }"
You absolutely should not have to do this and it made no sense to me why it would be have this way, but alas, I tried it and it worked :(