Javascript validation is not working in aspx page for allvalidate() - javascript

Here is my code:
<script type="text/javascript">
function Allvalidate() {
var ValidationSummary = "";
ValidationSummary += NameValidation;
ValidationSummary += EmailValidation;
ValidationSummary += MobilenumValidation;
if (ValidationSummary != "") {
alert("ValidationSummary");
return false;
}
else {
alert("Information Submitted Successfuly");
return true;
}
}
function NameValidation() {
var userid;
var controlid = document.getElementById("<%=Textusername.ClientID%>");
userid = controlid.value;
var val = /^[a-zA-Z]+$/;
if (userid == "") {
alert ("Enter your name" + "\n");
}
if (val.test(userid))
{
return "";
}
else{
alert("Name accepts only spaces and character" + "\n");
}
}
function EmailValidation() {
var userid;
var controlid = document.getElementById("<%=Textemail.ClientID%>");
userid = controlid;
var val = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (userid == "") {
alert("Enter your name" + "\n");
}
if (val.test(userid)) {
return "";
}
else {
alert("Email should be like this example xyz#abc.com");
}
}
function MobilenumValidation()
{
var userid;
var controlid = document.getElementById("<%=Textmobilenum.ClientID%>");
userid = controlid;
var val = /^[\d\.\-]+$/;
if (userid == "") {
alert("Enter your Mobile Number" + "\n");
}
if (val.test(userid)) {
return "";
}
else {
alert("PhoneNumber should be only in digits ");
}
}
</script>
aspx:
<asp:Button ID="btnsub" runat="server" Text="Submit"
OnClick="btnsub_Click" OnClientClick="javascript:Allvalidate()" />
The above code is not working, if i enter invalid mobile number,name and email it will accepted.
May i know, what is my mistake?
Thanks,

Related

jQuery validate textbox 1 if there is same multiple value inside textbox 2

I have 2 textbox.
<input type="text" id="pcbaSerialNo"/>
and
<input type="text" id="pcbaSerialNoMask"/>
and the js
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
The js function will run on enter key in textbox.
When scan on textbox #pcbaSerialNo, it will send the value to #pcbaSerialNoMask. (Example more than 1 value will be: test1, test2)
Now I need to validate #pcbaSerialNo to detect if there is same value.
My question, how to validate that textbox to prevent same value(duplicate)?
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="pcbaSerialNo"/>
<input type="text" id="pcbaSerialNoMask"/>
Just add below line before checking for existing value. You have to convert the string value to array while using inArray function.
pcbaSerialNoMask = pcbaSerialNoMask.split(",");
function handlePCBASerialNo(e)
{
var pcbaSerialNo = $(this).val();
var pcbaSerialNoMask = $('#pcbaSerialNoMask').val();
if(e.which ==13)
{
if(pcbaSerialNo == "")
{}
else
{
pcbaSerialNoMask = pcbaSerialNoMask.split(",");
if(jQuery.inArray(pcbaSerialNo, pcbaSerialNoMask) != -1)
{
alert("Duplicate scan is not allowed!");
}
else
{
if(pcbaSerialNoMask == "")
{
$('#pcbaSerialNoMask').val(pcbaSerialNo);
$('#totalScan').val("1");
}
else
{
var totalScan = $('#totalScan').val();
$('#pcbaSerialNoMask').val(pcbaSerialNo + "," + pcbaSerialNoMask);
$('#totalScan').val(parseInt(totalScan) + 1);
}
}
$('#pcbaSerialNo').bind('keypress', handlePCBASerialNo);
$('#pcbaSerialNo').val("");
}
}
}
$('#pcbaSerialNo').keypress(handlePCBASerialNo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" id="pcbaSerialNo"/>
<input type="text" id="pcbaSerialNoMask"/>

javascript validation with email check

when email are already existed, validation is hit the form action redirect the
page.i wanted to if email and all field are right way then hit the action part.
ajax success function not to return properly.
<script language="javascript">
function validate()
{
var str = true;
document.getElementById("msg1").innerHTML = "";
document.getElementById("msg2").innerHTML = "";
document.getElementById("msg3").innerHTML = "";
document.getElementById("msg4").innerHTML = "";
document.getElementById("msg5").innerHTML = "";
document.getElementById("msg6").innerHTML = "";
document.getElementById("msg7").innerHTML = "";
document.getElementById("msg8").innerHTML = "";
document.getElementById("msg9").innerHTML = "";
document.getElementById("msg10").innerHTML = "";
document.getElementById("msg11").innerHTML = "";
if (!document.frm.firstname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.firstname.value.match(patterns))
{
document.getElementById("msg1").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg1").innerHTML = "Please Enter First Name";
str = false;
}
if (!document.frm.lastname.value == '')
{
var patterns = /^[a-zA-Z\s]*$/;
if (!document.frm.lastname.value.match(patterns))
{
document.getElementById("msg2").innerHTML = "Please Enter only letters";
str = false;
}
} else
{
document.getElementById("msg2").innerHTML = "Please Enter Last Name";
str = false;
}
if (document.frm.password.value == '')
{
document.getElementById("msg4").innerHTML = "Please Enter Password";
str = false;
}
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!document.frm.phone.value.match(phoneno))
{
document.getElementById("msg5").innerHTML = "Please Enter 10 Digits Mobiles";
str = false;
}
if (document.frm.country.value == '')
{
document.getElementById("msg6").innerHTML = "Please Enter Country";
str = false;
}
if (document.frm.state.value == '')
{
document.getElementById("msg7").innerHTML = "Please Enter State";
str = false;
}
if (document.frm.city.value == '')
{
document.getElementById("msg8").innerHTML = "Please Enter City";
str = false;
}
if (document.frm.address.value == '')
{
document.getElementById("msg9").innerHTML = "Please Enter Address";
str = false;
}
if (document.frm.industry.value == '')
{
document.getElementById("msg10").innerHTML = "Please Select Industry";
str = false;
}
if (document.frm.company.value == '')
{
document.getElementById("msg11").innerHTML = "Please Enter Company Name";
str = false;
}
if (!document.frm.email.value == '')
{
var validate_char = /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\#(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/;
if (!document.frm.email.value.match(validate_char))
{
document.getElementById("msg3").innerHTML = "Please Enter Valid Email ID";
str = false;
} else {
var Email = document.frm.email.value;
var datastring = 'Email=' + Email;
$.ajax({
type: "POST",
url: "client_email.php",
data: datastring,
success: function(responseText) {
if (responseText == 1)
{
$("#msg3").html("Email Is Already Exists");
str = false;
}
}
});
}
} else
{
document.getElementById("msg3").innerHTML = "Email Field Is Empty";
str = false;
}
return str;
}
</script>
Use HTML5's new type attributes to accomplish this..
For email validity write:
<input type="email" name="email" required/>
and if the email is empty or wrong manner ,it will never hit submit event..Hence will not be redirected...
For eg:https://www.w3schools.com/code/tryit.asp?filename=FNZQV8G6AJ8P
for more types:https://www.w3schools.com/html/html_form_input_types.asp
Server Side:
Form Required Every Field By PHP
Form Type Validation By PHP

Cant get the session value using javascript in C#

I am trying to get 4 values from the session,while i get two of them,other two are missing.i am still learning so please bear with me if my question is too naive.I have this checkbox and two radio buttons in a tree view.
ASP.NET Code
<div class="control-label col-sm-1">
<asp:TreeView runat="server" ID="tvAi" Font-Bold="true" ShowLines="true" EnableClientScript="true"
ShowExpandCollapse="true" ShowCheckBoxes="All" >
</asp:TreeView>
<asp:HiddenField ID="hdMobile" runat="server" />
</div>
Now when i go to the chrome developer tool and check the values of the radio button the session values are binding well and shows like this.
<input type="radio" checked="checked" id="rad_01-02-00000622" name="rdoC1" value="01-02-00000622_Deposit_1_109861">
Those four values separated by '_' are accountNumber_accountType_officeId_customerId respectively.
The Javascript Code which sets session
$(function() {
$("[id*=tvAi] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("[id*=tvAi] input[type=radio]").bind("click",
function() {
//hdMobile
var parentDIV = $(this).closest("DIV");
if ($(this).is(":checked")) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
$("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
} else {
$("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
}
});
$("#SaveButton").bind("click",
function(e) {
$("#hdMobile").val("");
var tv = document.getElementById("<%= tvAi.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
if ($("#hdMobile").val() == "" || $("#hdMobile").val() == null) {
$("#hdMobile").val(chkArray[i].value);
} else {
$("#hdMobile").val($("#hdMobile").val() + "," + chkArray[i].value);
}
}
}
}
});
});
My Code behind setting the session
[WebMethod]
public static void SetSession()
{
System.Web.HttpContext.Current.Session["AccountMoney"] = "";
}
And binding treeview code
private void BindTreeViewForMobile()
{
_customerId = Convert.ToInt64(Session["CustomerId"]);
if (_customerId > 0)
{
DataTable dtAccount = new DataTable();
dtAccount = BusinessLayer.SMS.SmsSetup.GetActiveAccountListByCustomer(_customerId);
tvAi.Nodes.Clear();
int redindex = 1;
string accNumber = "";
var customerMobileBanking = BusinessLayer.SMS.MobileBankingSetup.GetMobileBankingCustomer(_customerId);
foreach (DataRow dr in dtAccount.Rows)
{
if (customerMobileBanking != null)
{
foreach (Common.SMS.MobileBankingSetup ss in customerMobileBanking)
{
if (ss.AccountNumber == dr["account_number"].ToString())
{
if (ss.FeeCharges)
{
accNumber = ss.AccountNumber;
break;
}
else
{
accNumber = "";
break;
}
}
}
}
TreeNode master = new TreeNode(dr["account_number"].ToString(), dr["account_number"].ToString());
master.ShowCheckBox = true;
tvAi.Nodes.Add(master);
master.SelectAction = TreeNodeSelectAction.None;
string sk = "";
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
master.Checked = true;
}
}
for (int i = 0; i <= 1; i++)
{
TreeNode child = new TreeNode(sk, sk);
child.SelectAction = TreeNodeSelectAction.None;
child.ShowCheckBox = false;
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
child.Text = "<input type='radio' checked='checked' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
}
else
{
child.Text = "<input type='radio' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
master.ChildNodes.Add(child);
}
redindex++;
}
}
}
The problem happens here when i am trying to get the session value in here
var sess = System.Web.HttpContext.Current.Session["AccountMoney"].ToString();
Here i only get the two session value not all 4.What am i doing wrong?Code must be too long for your time.any help appreciated.Thanks
I faced this before and search got me nowhere, went ahead and used cookies for the values I wanna read from JS. it works like a charm! Try it Get Cookies by name JS

JavaScript validation form integratation into one

I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}

set focus to textbox form element following Validation

I have a number of fields on a form that I perform Validation on, which I then want to Focus on if the validation fails. The Validation works fine, i.e. rtnStr, but the focus() just won't land on any of the textbox fields, i.e. vCtrl. It remains on the Submit button.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = "txtforename";
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = "txtSurname";
}
}
if (rtnStr != "") {
alert(rtnStr)
window.setTimeout(function () {
document.getElementById(vCtrl).focus();
}, 0);
return false;
}
else {
return true;
}
}
</script>
The problem is that vCtrl is a string which is the name of a form and not the id which document.getElementById(vCtrl).focus() is looking for. The way to fix this is to make vCtrl store the DOM element instead of a text string.
<script language="javascript">
function ValidateForm() {
var rtnStr = "";
var vCtrl = "";
//Contact Details //
if (document.contactform.txtforename.value == "") {
rtnStr = rtnStr + " - Please enter your Forename.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtforename;
}
}
if (document.contactform.txtSurname.value == "") {
rtnStr = rtnStr + " - Please enter your Surname.\n"
if (vCtrl == "") {
vCtrl = document.contactform.txtSurname;
}
}
if (rtnStr != "") {
alert(rtnStr)
vCtrl.focus();
return false;
}
else {
return true;
}
}
</script>
jsfiddle

Categories