Javascript showing alert without refreshing the page - javascript

when I click submit button it shows the validation right but after that alert message the page is being refreshed and i loos all other datas from the fields :S, how can i make it to still remain the others field filled.
I tried to remove the window.location.reload() after submit event is called but still not working :S. ANYONE any suggestion?
this is the code:
function formValidation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;
if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}

Two problems...
Missing return
onSubmit="return formValidation();"
Missing return true;
if (validsex(umsex, ufsex)) { return true; }

Related

Why my below javascript code in asp.net not working?

<script language="javascript" type="text/javascript">
function validate() {
summary += isvalidFirstName();
summary += isvalidMobile();
summary += checkPassword();
summary += checkEmail();
if (summary != "") {
alert(summary);
return false;
} else
return true;
}
function isvalidFirstName() {
var uid;
var temp = document.getElementById("<%=txtFirstName.ClientID %>");
uid = temp.value;
if (uid == "") {
return ("Please enter firstname" + "\n");
} else
return "";
}
function isvalidMobile() {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMob = document.getElementById(txtMobile);
if (mob.test(txtMob.value) == false) {
alert("Please enter valid mobile number");
txtMob.focus();
return false;
} else
return true;
}
function checkPassword(inputtxt) {
var pass = /^[A-Za-z]\w{7,14}$/;
if (inputtxt.value.match(pass)) {
alert("Password is correct");
return true;
} else {
alert("Wrong...!");
return false;
}
}
function checkEmail(inputtxt) {
var mail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputtxt.value.match(mail)) {
return true;
} else {
alert("Please enetr a valid email id");
return false;
}
}
</script>
I have added the above javascript code inside an .ASPX page and called the function validate on button click but it is not working. Can anyone help me?

Showing multiple validation alert on button click

I have written a Jquery code for validation. But the problem here is that, First the regular expression message fires and after that requiredField error message fires.
Here is my code:-
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTextBoxes();
function FunValidatePan()
if (ErrArr.length > 0)
{
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTextBoxes() {
if ($("#txtPanNo").val() === "") {
ErrArr.push('Pan No is required');
}
}
function FunValidatePan() {
var StrPriError = "";
if (Trim(document.getElementById("txtPanNo").value) != "" && Trim(document.getElementById("txtPanNo").value) != "NULL") {
var fil = /^[a-zA-Z0-9]+$/;
if (fil.test(document.getElementById("txtPanNo").value)) {
var abc = Trim(document.getElementById("txtPanNo").value);
if (abc.length != 10) {
StrPriError += ' Enter valid PAN Card\n';
}
}
else {
StrPriError += ' Enter valid PAN Card\n';
}
}
if (StrPriError != "") {
alert(StrPriError);
return false;
}
else {
return true;
}
}
I want that in single message. How to achieve that. Please suggest. Also I want that in Jquery
UPDATE
ASPX
<asp:TextBox ID="txtPanNo" runat="server" Width="100" MaxLength="10"></asp:TextBox>
Please check changes in the above code.
var ErrArr = [];
$(document).ready(function () {
$('#btnSave').click(function (e) {
e.preventDefault();
validateTextBoxes();
FunValidatePan();
if (ErrArr.length > 0)
{
alert(ErrArr.join("\n"));
ErrArr = [];
return false;
}
});
function validateTextBoxes() {
if ($("#txtPanNo").val() === "") {
ErrArr.push('Pan No is required');
}
}
function FunValidatePan() {
if (Trim(document.getElementById("txtPanNo").value) != "" && Trim(document.getElementById("txtPanNo").value) != "NULL") {
var fil = /^[a-zA-Z0-9]+$/;
if (fil.test(document.getElementById("txtPanNo").value)) {
var abc = Trim(document.getElementById("txtPanNo").value);
if (abc.length != 10) {
ErrArr.push('Enter valid PAN Card');
}
}
else {
ErrArr.push('Enter valid PAN Card');
}
}
}

Do not allow special characters jQuery

Have some error in this, can you guys please tell me what i am doing wrong
function verifyGroup(groupVal, errorid) {
groupVal = $.trim(groupVal);
if (groupVal != '') {
var splChars = "*|,\":<>[]{}`\';()#&$#%!+-";
for (var i = 0; i < groupVal.length; i++) {
console.log(groupVal.charAt(i)+' == '+splChars.indexOf(groupVal.charAt(i)));
if (splChars.indexOf(groupVal.charAt(i)) != -1) {
$("#" + errorid).addClass("form-error").html("Illegal characters detected!");
return false;
} else {
$("#" + errorid).removeClass("form-error").html("");
return true;
}
}
} else {
$("#" + errorid).addClass("form-error").html("Group name should not be empty");
return false;
}
}
DEMO
Use a regex
function verifyGroup(groupVal, errorid) {
groupVal = $.trim(groupVal);
console.log(groupVal);
console.log(errorid);
if (groupVal != '') {
var regex = /[*|,\\":<>\[\]{}`';()#&$#%!+-]/;
if(regex.test(groupVal)){
$("#" + errorid).addClass("form-error").html("Illegal characters detected!");
return false;
} else {
$("#" + errorid).removeClass("form-error").html("valid");
return true;
}
} else {
$("#" + errorid).addClass("form-error").html("Group name should not be empty");
return false;
}
}
$(function() {
// Handler for .ready() called.
$('#submit').click(function(){
verifyGroup($('#ipId_create').val(), 'error_id');
});
});
Demo: Fiddle
The comparison to -1 should be == not !=.

retain form values onclick after javascript validation fails

This is part of an assignment. Everything that's supposed to work, already works, but there's something that bothers me. The only purpose of the code so far is to test our ability to validate from data. Anyway, right now the validate() function is attached to a submit button:
<input type="submit" value="Find Love" onclick="validate()">
When any validation fails, all the text boxes, drop downs, etc. are cleared, but I want them to retain their values and just focus on the first incorrect value (retaining their values is more important to me at this point). The actual Does that require some modification of the onclick function or a different function all together? Please help. If you need to see the javascript I can post that as well.
function validate()
{
var blnValid = true;
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!")
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!")
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!")
document.getElementById("txtAge").focus();
}
}
if(blnValid)
{
var strInput = document.getElementById("txtAge").value;
if(!isInt(strInput))
{
blnValid = false;
alert("You must enter a valid number in the age field.")
document.getElementById("txtAge").select();
}
}
if(blnValid)
{
if(document.getElementById("selUserGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
if(document.getElementById("selFindGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
blnChecked = false;
arRadio = document.forms[0].rdbAgeRange;
for (var i = 0; i < arRadio.length; i++)
{
if(arRadio[i].checked)
{
blnChecked = true;
break;
}
}
if (!blnChecked)
{
alert("You must select an age group.");
blnValid = false;
}
}
if(blnValid)
{
if(!document.getElementById("chkSkeeball").checked
&& !document.getElementById("chkAir").checked
&& !document.getElementById("chkCliff").checked
&& !document.getElementById("chkHamster").checked)
{
blnValid = false;
alert("You must select a hobby.")
}
}
return blnValid;
}
function isInt(strValue)
{
var validNums = "0123456789";
var blnIsNumber = true;
var tempChar;
for (var i = 0; i < validNums.length; i++)
{
tempChar = strValue.substr(i, 1);
if (validNums.indexOf(tempChar) == -1)
{
return false;
}
}
return true;
}
function isBlank(elementID)
{
if(document.getElementById(elementID).value.length == 0)
{
return true;
}
return false;
}
Your problem is actually your HTML. Nothing in your Javascript is going to clear the elements but because you're using onClick the form is actually submitting anyway. I assume that it probably just submits back to the page and clears everything. Instead of onClick use onSubmit in the form element:
<form method="post" action="url_of_action" onSubmit="return validate()">
If it's not valid it will prevent the form from submitting.
Missing semi-colons:
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!") //here
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!") //and here
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!") //and here
document.getElementById("txtAge").focus();
}
}

Null error is coming document.getElementByid("dthchannel" + [i] is null)

function validate()
{
var flag=0;
var spchar=/^[a-zA-Z0-9 ]*$/;
var num=/^[0-9]*$/;
var custid = document.getElementById('CUSTOMERID').value;
var phoNo = document.getElementById('PHONENO').value;
var emailId = document.getElementById('EMAILID').value;
var channel = document.getElementById('CHANNELDTL').value;
if(channel=="")
{
alert("You have not selected any channel");
flag=1;
return false;
}
if(custid=="" || custid==null )
{
alert("Please enter Customer ID");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if (custid.search(num)==-1)
{
alert("Customer should be Numeric");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if(phoNo=="" || phoNo==null )
{
alert("Please enter Phone");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if (phoNo.search(num)==-1)
{
alert("Phone should be Numeric");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if(emailId=="" || emailId==null )
{
alert("Please enter Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
if (emailId)
{
if(isValidEmail(document.getElementById('EMAILID').value) == false)
{
alert("Please enter valid Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
}
if(flag==0)
{
var emailid=Base64.tripleEncoding(document.getElementById('EMAILID').value);
document.getElementById('E_EMAIL').value=emailid;
document.getElementById('EMAILID').value="";
var mobileno=Base64.tripleEncoding(document.getElementById('PHONENO').value);
document.getElementById('E_PHONE').value=mobileno;
document.getElementById('PHONENO').value="";
var customerid=Base64.tripleEncoding(document.getElementById('CUSTOMERID').value);
document.getElementById('E_CUSTID').value=customerid;
document.getElementById('CUSTOMERID').value="";
document.topupsform.action="../dth/leads/channelMail/channelMailUtil.jsp";
document.topupsform.submit();
alert("Thank you for choosing A-La-Carte services.\nWe will process it within 24 hours.\nYou will soon receive confirmation on your mail id.");
}
}
function isValidEmail(Email)
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = trim(Email);
if(reg.test(address) == false)
{
return false;
}
else
return true;
}
function trim(str)
{
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function sendMail()
{
caltotal();
validate();
}
//----------------------------------
var counter = 0;
function resetcheckboxValue(){
//var totalinputs = document.topupsform.getElementsByTagName("input");
var totalinputs =document.getElementsByName("dthchannel");
var totallenght = totalinputs.length;
counter = 0;
for(var i = 0; i < totallenght; i++) {
// reset all checkboxes
document.getElementsByName("dthchannel")[i].checked = false;
document.getElementById("totalamount").value = "0";
document.getElementById("youpay").value = "0";
}
}
function caltotal()
{
var plansObj = document.getElementsByName("dthchannel");
var plansLength = plansObj.length;
counter = 0;
var finalNameValue = "";
for(var i = 1; i <= plansObj.length+1; i++) {
if ( document.getElementById(("dthchannel")+ [i]).checked)
{
var gvalue = parseInt(document.getElementById(("dthchannel")+[i]).value);
var gNameValue= document.getElementById("CHANNELNAME"+i).value+"~"+gvalue+"#";
finalNameValue+= gNameValue;
counter+= gvalue;
}
showresult();
}
var finallist = finalNameValue.substring(0,finalNameValue.length-1);
//alert("finallist" +finallist);
document.getElementById("CHANNELDTL").value= finallist;
}
function showresult(){
if(counter <= 150 && counter > 0){
document.getElementById("youpay").value = "150";
document.getElementById("totalamount").value = counter;
}
else
{
document.getElementById("youpay").value = counter;
document.getElementById("totalamount").value = counter;
}
}
window.onload = resetcheckboxValue;
You need to modify whatever lines look like this:
var gvalue = parseInt(document.getElementById("dthchannel" + i).value);
You don't want to do document.getElementById(("dthchannel") + [i]) as I've never seen that before and I don't think it works.

Categories

Resources