Javascript, Jquery, HTML - javascript

How can i add prevent-default() with focus-out() in my form. I face problem when i click the reset button in my form. It show the last focusing input field error message when i click the reset button. Here my code bellow:
$(document).ready(function(){
//error message section:
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
//username validation area:
function checkUsername(){
var name = $("#username").val();
var usernameLength = $("#username").val().length;
if(!name.replace(/\s/g, '').length){
$("#username_error_msg").html("<span class='errorMessage'>Username shouldn't be empty..!</span>").slideDown(500);
}else if(usernameLength < 5 || usernameLength > 20){
$("#username_error_msg").html("<span class='errorMessage'>Username should be between 5-20 characters..!</span>").slideDown(500);
}else{
$("#username_error_msg").slideUp(500);
return true;
}
}
//Gender selection check:
function checkGenderSelection(){
var genderCategory = $('select[name=Gender]').val();
if(genderCategory == 'Select'){
$("#gender_Select_error_msg").html("<span class='errorMessage'>Please select your gender..!</span>").slideDown(500);
}else if((genderCategory == 'Male') || (genderCategory == 'Female')){
$("#gender_Select_error_msg").slideUp(500);
return true;
}
}
//job category check: radiobutton
function checkJobCategorySelection(){
var jobCategory = $('input[name=jobCategory]:checked');
if(jobCategory.length == 0){
$("#jobCategory_error_msg").html("<span class='errorMessage'>No Category Selected..!</span>").slideDown(500);
}else{
$("#jobCategory_error_msg").slideUp(500);
return true;
//By this way we can collect the value from radio button for further action//
//console.log("Selected Item: " + jobCategory.val());
}
}
//programming Experience check: checkbox
function programmingExperienceCheck(){
var experienceList = $('input:checkbox[name=language]:checked');
if(experienceList.length == 0){
$("#experience_sector_error_msg").html("<span class='errorMessage'>No Sector Selected..!</span>").slideDown(500);
}else{
$("#experience_sector_error_msg").slideUp(500);
return true;
}
}
//password validation area:
function checkPassword(){
var pass = $("#password").val();
var passwordLength = $("#password").val().length;
if(!pass.replace(/\s/g, '').length){
$("#password_error_msg").html("<span class='errorMessage'>Please type your password..!</span>").slideDown(500);
}else if(passwordLength < 8){
$("#password_error_msg").html("<span class='errorMessage'>Password should be minimum 8 characters..!<span class='errorMessage'>").slideDown(500);
}else{
$("#password_error_msg").slideUp(500);
return true;
}
}
//retype password validation area:
function checkRetypePassword(){
var pass = $("#password").val();
var retypePass = $("#retype_password").val();
if(!retypePass.replace(/\s/g, '').length){
$("#retype_password_error_msg").html("<span class='errorMessage'>Please give your password again..!</span>").slideDown(500);
}
else if(pass !== retypePass){
$("#retype_password_error_msg").html("<span class='errorMessage'>Password don't match..!</span>").slideDown(500);
}else{
$("#retype_password_error_msg").slideUp(500);
return true;
}
}
//email validation area:
function checkEmail(){
var regularExp = new RegExp(/([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})/);
if(!$("#email").val().replace(/\s/g, '').length){
$("#email_error_msg").html("<span class='errorMessage'>Please give your email id..!</span>").slideDown(500);
}
else if(regularExp.test($("#email").val())){
$("#email_error_msg").slideUp(500);
return true;
}else{
$("#email_error_msg").html("<span class='errorMessage'>Invalid Email..!</span>").slideDown(500);
}
}
//phone number validation area:
function checkPhoneNumber(){
var phone_number = $("#phoneNo").val();
var regularExp = new RegExp(/^(?:\+?88)?01[15-9]\d{8}$/);
if(!phone_number.replace(/\s/g, '').length){
$("#phone_no_error_msg").html("<span class='errorMessage'>Please enter a phone number..!</span>").slideDown(500);
}else if(regularExp.test($("#phoneNo").val())){
$("#phone_no_error_msg").slideUp(500);
return true;
}else{
$("#phone_no_error_msg").html("<span class='errorMessage'>Invalid phone number..!</span>").slideDown(500);
}
}
//short notes validation area:
function checkShortNotes(){
var shortNotes = $("#short_note").val();
var shortNotesLength = $("#short_note").val().length;
if(!shortNotes.replace(/\s/g, '').length){
$("#short_note_error_msg").html("<span class='errorMessage'>You have to write something about you..!</span>").slideDown(500);
}else if(shortNotesLength < 10){
$("#short_note_error_msg").html("<span class='errorMessage'>Your notes is too short..!</span>").slideDown(500);
}else{
$("#short_note_error_msg").slideUp(500);
return true;
}
}
//username focus action:
$("#username").focusout(function(){
if($('input[type=reset]').data('clicked',false)){
checkUsername();
}
});
//gender focus action:
$("#gender").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkGenderSelection();
}
});
//password focus action:
$("#password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPassword();
}
});
//retypePassword focus action:
$("#retype_password").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkRetypePassword();
}
});
//email focus action:
$("#email").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkEmail();
}
});
//phone number focus action:
$("#phoneNo").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkPhoneNumber();
}
});
//shortNotes focus action:
$("#short_note").focusout(function(){
if($('input[type=reset]').data('clicked',false)) {
checkShortNotes();
}
});
//form submit action:
$("#myForm").submit(function(){
if(checkUsername() && checkGenderSelection() && checkJobCategorySelection() && programmingExperienceCheck() && checkPassword() && checkRetypePassword() && checkEmail() && checkPhoneNumber() && checkShortNotes()){
return true;
}
else{
return false;
}
});
});
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
});
.errorMessage{background-color: darkcyan;color:white; border-radius:2px;font-size: 15px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" action="msg.php" method="post">
<table>
<tr>
<td>Username: </td>
<td><input type="text" id="username"></td>
<td><span id="username_error_msg"></span></td>
</tr>
<tr>
<td>Select Your Gender: </td>
<td>
<select name="Gender" id="gender">
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
<td><span id="gender_Select_error_msg"></span></td>
</tr>
<tr>
<td>Select Job Category: </td>
<td>
<input type="radio" name="jobCategory" value="Part Time"/> Part Time
<input type="radio" name="jobCategory" value="Full Time"/> Full Time
<input type="radio" name="jobCategory" value="Intern"/> Intern
</td>
<td><span id="jobCategory_error_msg"></span></td>
</tr>
<tr>
<td>Select Experience Sector:</td>
<td>
<input type="checkbox" name="language"/> Javascript
<input type="checkbox" name="language"/> PHP
<input type="checkbox" name="language"/> Jquery
</td>
<td><span id="experience_sector_error_msg"></span></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" id="password"></td>
<td><span id="password_error_msg"></span></td>
</tr>
<tr>
<td>Retype Password: </td>
<td><input type="password" id="retype_password"></td>
<td><span id="retype_password_error_msg"></span></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" id="email"></td>
<td><span id="email_error_msg"></span></td>
</tr>
<tr>
<td>Phone No: </td>
<td><input type="text" id="phoneNo"></td>
<td><span id="phone_no_error_msg"></span></td>
</tr>
<tr>
<td>Short Note About You: </td>
<td><textarea id="short_note" cols="22" rows="5"></textarea></td>
<td><span id="short_note_error_msg"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit"/>
<input type="reset" value="Refresh"/>
</td>
<td></td>
</tr>
</table>
</form>
});
How can i stop to seeing any focus-out() action when i click reset button????

When you reset the form, you are hiding all the error messages. Then focus on the first element - username.
//refresh button action:
$('input[type=reset]').click(function(){
$("#username_error_msg").hide();
$("#gender_Select_error_msg").hide();
$("#jobCategory_error_msg").hide();
$("#experience_sector_error_msg").hide();
$("#password_error_msg").hide();
$("#retype_password_error_msg").hide();
$("#email_error_msg").hide();
$("#phone_no_error_msg").hide();
$("#short_note_error_msg").hide();
$('#username').focus();
});

Blur comes before click so you are setting the .html of the error, then the click comes and you hide it but because you use .slide jQuery will then set it visible again as it's sliding in.
The simplest way would be to set the html of the error to an empty string, jQuery can then slide in an empty string:
function removeErrors(){
$("#username_error_msg").html("");
$("#gender_Select_error_msg").html("");
$("#jobCategory_error_msg").html("");
$("#experience_sector_error_msg").html("");
$("#password_error_msg").html("");
$("#retype_password_error_msg").html("");
$("#email_error_msg").html("");
$("#phone_no_error_msg").html("");
$("#short_note_error_msg").html("");
}
//refresh button action:
$('input[type=reset]').click(function(){
removeErrors();
});

Related

Submit button is not getting enabled after checking all the fields

I have a sign up form where I have taken some basic details of the customer and a Submit button.
I have validate all the fields using ajax but confirm password field using javascript. When I write code only using Ajax and not validating Confirm password field it is running perfectly but the problem is when I am validation it using JS submit button is not getting enable.
Sign up form:
<html>
<head>
<title> Registration Form </title>
<script language="javascript">
var flag = false;
function validate(element)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new Activexobject("Microsoft.XMLHTTP");
}
var myField = element;
xmlhttp.open('GET', 'validate.php?' + myField.id + "=" + myField.value, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function ()
{
//alert("Hello");
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var response = xmlhttp.responseText.split("||");
//alert("H2");
}
var divname = "err" + myField.id.substring(3);
var mydiv = document.getElementById(divname);
if (!eval(response[0]))
{
//alert("Fail");
//alert("Value: "+response);
mydiv.innerHTML = response[1];
myField.valid = false;
}
else
{
//alert("Success");
myField.valid = true;
mydiv.innerHTML = "";
}
var btn = document.getElementById("btnSubmit");
btn.disabled = !isValidForm();
}
}
;
function password()
{
var pass = document.getElementById("txtpswd").value;
var Confirm_pass = document.getElementById("txtConfirmpassword").value;
alert("Pass " + pass);
alert("Confirm: " + Confirm_pass);
if (pass == Confirm_pass)
{
flag = true;
alert("True");
document.getElementById("errConfirmpassword").innerHTML = "";
}
else
{
alert("False");
flag = false;
document.getElementById("errConfirmpassword").innerHTML = "Password does not Match";
}
}
;
function isValidForm()
{
var f1 = document.getElementById("txtfname");
var f2 = document.getElementById("txtlname");
var f3 = document.getElementById("txtaddress");
var f4 = document.getElementById("txtzip");
var f5 = document.getElementById("txtnumber");
var f6 = document.getElementById("txtmail");
var f7 = document.getElementById("txtpswd");
var f8 = document.getElementById("txtConfirmpassword");
return(f1.valid && f2.valid && f3.valid && f4.valid && f5.valid && f6.valid && f7.valid && f8.valid);
}
;
</script>
</head>
<body>
<center>
<h1><font color="red"> New User Registration Form </font></h1>
<form name="SignUpForm" method="POST" action="function_customer.php?val=insert">
<table>
<tr>
<td id=q> <font face="Century Schoolbook"> First Name :</font></td> <br>
<td> <input type=text name=txtfname id="txtfname" placeholder=First_name onchange="validate(this);" valid=false> </td>
<td><div id="errfname"/></td>
</tr>
<tr>
<td id=q> Last Name :</td>
<td> <input type=text name=txtlname id="txtlname" placeholder=Last_Name onchange="validate(this);" valid=false> </td>
<td><div id="errlname"/></td>
</tr>
<tr>
<td id=q>Address : </td><br>
<td> <textarea rows=5 cols=20 name="txtaddress" id="txtaddress" onchange="validate(this);" valid=false>
</textarea>
</td>
<td><div id="erraddress"/></td>
</tr>
<tr>
<td id=q> Contact no : </td>
<td> <input type=text name="txtnumber" id="txtnumber" onchange="validate(this);" valid=false> </td>
<td><div id="errnumber"/></td>
</tr>
<tr>
<td id=q> Gender </td>
<td> <select name="txtcity" id="gender">
<option value="Male"> Male </option>
<option value="Female"> Female </option>
</select>
</td>
</tr>
<tr>
<td id=q> City </td>
<td>
<select name="txtcity" id="txtcity">
<option> City </option>
<option value="Vadodara"> Vadodara </option>
<option value="Ahmedabad"> Ahmedabad </option>
<option value="Surat"> Surat </option>
<option value="Rajkot"> Rajkot </option>
<option value="Bhavnagar">Bhavnagar</option>
<option value="Jamnagar">Jamnagar</option>
<option value="Nadidad">Nadidad</option>
<option value="Morvi">Morvi</option>
<option value="Gandhidham">Gandhidham</option>
<option value="Adipur">Adipur</option>
<option value="Anand">Anand</option>
<option value="Baruch">Baruch</option>
<option value="Godhra">Godhra</option>
<option value="Veraval">Veraval</option>
<option value="Navsari">Navsari</option>
</select>
</td>
</tr>
<tr>
<td id=q> ZIP : </td>
<td> <input type=text name=txtzip id="txtzip" onchange="validate(this);" valid=false> </td>
<td><div id="errzip"/></td>
</tr>
<tr>
<td id=q> Email Id : </td>
<td> <input type="email" name=txtmail placeholder=someone#exe.com id="txtmail" onchange="validate(this);" valid=false> </td>
<td><div id="errmail"/></td>
</tr>
<tr>
<td id=q> New Password : </td>
<td> <input type="password" name="txtpswd" id="txtpswd" onchange="validate(this);" valid=false>
</td>
<td><div id="errpswd"/></td>
</tr>
<tr>
<td id=q>Confirm Password : </td><td><input type="password" name=txtConfirmpassword id="txtConfirmpassword" onchange="password();" valid=false>
</td>
<td><div id="errConfirmpassword"/></td>
</tr>
<tr>
<td></td><td><input type=reset name=reset value=Reset>
</td>
</tr>
<tr>
</tr>
</table>
</form>
<br>
<br>
<br>
<br><br>
</center>
</body>
</html>
What should I do to validate all the fields and enabling the Submit Button?
First of all I suggest you read up on the latest HTML elements and use CSS for centering or styling your elements and avoid usage of obsolete elements like <font> and <center>.
Having said that, the issue in your code is that you're not calling validate() to check if the form is valid after password & confirm password fields match, so change your password() like below.
function password(){
var btn = document.getElementById("btnSubmit");
var pass = document.getElementById("txtpswd").value;
var confirm_pass = document.getElementById("txtConfirmpassword").value;
var pwdErrorElement = document.getElementById("errConfirmpassword");
if (pass === confirm_pass){
flag = true;
pwdErrorElement.innerHTML = "";
btn.disabled = !isValidForm();
}else{
flag = false;
pwdErrorElement.innerHTML = "Password does not Match";
btn.disabled = true;
}
}
Also I suggest you to make use of value property on each field to do the validations on client side rather than making a server call for every field change. You can use field values for validations by changing the last statement in your isValidForm() like below.
function isValidForm(){
// get all the field references
return(f1.value && f2.value && f3.value && f4.value
&& f5.value && f6.value && f7.value && f8.value);
}
Once you're done with the JS validations, you can enable the submit button and do validations for all fields at once on your server side on form submit. I mean that's the very purpose of doing client side validations using JS. You don't want to ask for feedback (valid or not) for every field change.
Here's a working Pen with all the above changes.

My validation keeps giving me an alert even though I have filled the fields

I have a form like this:
<form id="formDaftar" onsubmit="return daftarClick()" method="post">
<table id="tableFormDaftar" border="0" width="400px" height="300px">
<tr>
<td>Nama</td>
<td><input type="text" name="nama" id="nama" size="39"/></td>
</tr>
<tr>
<td>Alamat</td>
<td><textarea cols="40" rows="4" name="alamat" id="alamat">
</textarea></td>
</tr>
<tr>
<td>Tempat/Tanggal Lahir</td>
<td><input name="tempatLahir" id="tempatLahir" size="39" type="text"/></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<td><input type="radio" id="radio1" name="gender" id="gender1"/>Laki-laki
<input type="radio" id="radio1" name="gender" id="gender2"/>Perempuan
</td>
</tr>
<tr>
<td>Pekerjaan</td>
<td><input name="pekerjaan" id="pekerjaan" size="39"/></td>
</tr>
<tr>
<td>Status</td>
<td>
<select id="status" name="status">
<option selected="selected">Lajang</option>
<option>Menikah</option>
<option>Duda</option>
<option>Janda</option>
</select></td>
</tr>
<tr>
<td>Agama</td>
<td><select id="agama" name="agama">
<option>Islam</option>
<option selected="selected">Kristen</option>
<option>Katholik</option>
<option>Budha</option>
<option>Hindu</option>
</select></td>
</tr>
<tr>
<td>Kewarganegaraan</td>
<td><select id="kwn">
<option selected="selected">Indonesia</option>
<option>Asing</option>
</select></td>
</tr>
<tr>
<td colspan="2" id="colbutton"> <button name="masukkan" type="submit" id="masukkan">Masukkan</button> <button type="reset" name="batalkan" id="batalkan">Batalkan</button></td>
</tr>
</table></form>
I have a script like this:
var nama = document.getElementById("nama").value;
var alamat = document.getElementById("alamat").value;
var tempatLahir = document.getElementById("tempatLahir").value;
var gender;
if (document.getElementById("gender1").checked){
gender = document.getElementById("gender1").value;
}
else if (document.getElementById("gender2").checked){
gender = document.getElementById("gender2").value;
}
var a = document.getElementById("agama");
var agama = a.options[a.selectedIndex].text;
var pekerjaan = document.getElementById("pekerjaan").value;
var b = document.getElementById("status");
var status = b.options[b.selectedIndex].text;
var c = document.getElementById("kwn");
var kwn = c.options[c.selectedIndex].text;
function daftarClick(){
if (nama == ""){
alert("Nama harus diisi!");
return false;
}
else if (alamat == ""){
alert("Alamat harus diisi!");
return false;
}
else if (tempatLahir == ""){
alert("Tempat/Tanggal Lahir harus diisi!");
return false;
}
else if(!document.getElementById("gender1").checked && !document.getElementById("gender2").checked){
alert("Jenis Kelamin harus dipilih!");
return false;
}
}
The problem is that even though I have filled the fields, it keeps showing the alert() saying that I need to fill the fields.
I have set the validation which will show an alert if the user had not put any letters in the fields but no matter what I put in the fields, it keeps saying that I haven't put it there. What did I get wrong here?
It is because your variables were declared at page load so then your inputs were empty and the variables got empty values
Change it to
<script type="text/javascript">
function daftarClick(){
var nama = document.getElementById("nama").value;
var alamat = document.getElementById("alamat").value;
var tempatLahir = document.getElementById("tempatLahir").value;
var gender;
if (document.getElementById("gender1").checked){
gender = document.getElementById("gender1").value;
}
else if (document.getElementById("gender2").checked){
gender = document.getElementById("gender2").value;
}
var a = document.getElementById("agama");
var agama = a.options[a.selectedIndex].text;
var pekerjaan = document.getElementById("pekerjaan").value;
var b = document.getElementById("status");
var status = b.options[b.selectedIndex].text;
var c = document.getElementById("kwn");
var kwn = c.options[c.selectedIndex].text;
if (nama == ""){
alert("Nama harus diisi!");
return false;
}
else if (alamat == ""){
alert("Alamat harus diisi!");
return false;
}
else if (tempatLahir == ""){
alert("Tempat/Tanggal Lahir harus diisi!");
return false;
}
else if(!document.getElementById("gender1").checked && !document.getElementById("gender2").checked){
alert("Jenis Kelamin harus dipilih!");
return false;
}
}
</script>
Try this:
<script type="text/javascript">
function daftarClick(){
var nama = document.getElementById("nama").value;
var alamat = document.getElementById("alamat").value;
var tempatLahir = document.getElementById("tempatLahir").value;
var gender;
if (document.getElementById("gender1").checked){
gender = document.getElementById("gender1").value;
}
else if (document.getElementById("gender2").checked){
gender = document.getElementById("gender2").value;
}
var a = document.getElementById("agama");
var agama = a.options[a.selectedIndex].text;
var pekerjaan = document.getElementById("pekerjaan").value;
var b = document.getElementById("status");
var status = b.options[b.selectedIndex].text;
var c = document.getElementById("kwn");
var kwn = c.options[c.selectedIndex].text;
if (nama == ""){
alert("Nama harus diisi!");
return false;
}
else if (alamat == ""){
alert("Alamat harus diisi!");
return false;
}
else if (tempatLahir == ""){
alert("Tempat/Tanggal Lahir harus diisi!");
return false;
}
else if(!document.getElementById("gender1").checked && !document.getElementById("gender2").checked){
alert("Jenis Kelamin harus dipilih!");
return false;
}
}
</script>
EDIT: The checkboxes in the HTML have multiple id attributes, which is an error, and thus document.getElementById cannot find them.
<form id="formDaftar" onsubmit="return daftarClick()" method="post">
<table id="tableFormDaftar" border="0" width="400px" height="300px">
<tr>
<td>Nama</td>
<td><input type="text" name="nama" id="nama" size="39"/></td>
</tr>
<tr>
<td>Alamat</td>
<td><textarea cols="40" rows="4" name="alamat" id="alamat">
</textarea></td>
</tr>
<tr>
<td>Tempat/Tanggal Lahir</td>
<td><input name="tempatLahir" id="tempatLahir" size="39" type="text"/></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<!-- Fix is here, id="radio1" removed from both -->
<td><input type="radio" name="gender" id="gender1"/>Laki-laki
<input type="radio" name="gender" id="gender2"/>Perempuan
</td>
</tr>
<tr>
<td>Pekerjaan</td>
<td><input name="pekerjaan" id="pekerjaan" size="39"/></td>
</tr>
<tr>
<td>Status</td>
<td>
<select id="status" name="status">
<option selected="selected">Lajang</option>
<option>Menikah</option>
<option>Duda</option>
<option>Janda</option>
</select></td>
</tr>
<tr>
<td>Agama</td>
<td><select id="agama" name="agama">
<option>Islam</option>
<option selected="selected">Kristen</option>
<option>Katholik</option>
<option>Budha</option>
<option>Hindu</option>
</select></td>
</tr>
<tr>
<td>Kewarganegaraan</td>
<td><select id="kwn">
<option selected="selected">Indonesia</option>
<option>Asing</option>
</select></td>
</tr>
<tr>
<td colspan="2" id="colbutton"> <button name="masukkan" type="submit" id="masukkan">Masukkan</button> <button type="reset" name="batalkan" id="batalkan">Batalkan</button></td>
</tr>
</table></form>
check this I think it is working as you are expecting
https://jsbin.com/ragoces/edit?html,js,output
var nama = document.getElementById("nama");
var alamat = document.getElementById("alamat");
var tempatLahir = document.getElementById("tempatLahir");
var gender;
if (document.getElementById("gender1").checked){
gender = document.getElementById("gender1").value;
}
else if (document.getElementById("gender2").checked){
gender = document.getElementById("gender2").value;
}
var a = document.getElementById("agama");
var agama = a.options[a.selectedIndex].text;
var pekerjaan = document.getElementById("pekerjaan").value;
var b = document.getElementById("status");
var status = b.options[b.selectedIndex].text;
var c = document.getElementById("kwn");
var kwn = c.options[c.selectedIndex].text;
function daftarClick(){
if (nama.value === ""){
alert("Nama harus diisi!");
return false;
}
else if (alamat.value === ""){
alert("Alamat harus diisi!");
return false;
}
else if (tempatLahir.value === ""){
alert("Tempat/Tanggal Lahir harus diisi!");
return false;
}
else if(!document.getElementById("gender1").checked && !document.getElementById("gender2").checked){
alert("Jenis Kelamin harus dipilih!");
return false;
}
}

form validation javascript (error message showed and disappeared quickly)

i want to show the error messages next to the input element and if there's no error messages then send the data to the server (clear data from form) so fire the function on submit
http://codepen.io/anon/pen/RPNpNw
the problem is the error messages showed and disappeared quickly (blink)
but when change the input type to button
http://codepen.io/anon/pen/EjaZqe
will work but the data will be still in form and not cleared as input type="submit" will do
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<form>
<table style="width:50%;">
<tr>
<td>first name</td>
<td><input type="text" id="txtfname" /></td>
<td><span id="error"></span></td>
</tr>
<tr>
<td>age</td>
<td><input type="number" id="txtage" onblur="checkAge(txtage)" /></td>
<td><span id="errorage"></span></td>
</tr>
<tr>
<td>user name</td>
<td><input type="text" id="txtuser" /></td>
<td><span id="erroruser"></span></td>
</tr>
<tr>
<td>country</td>
<td>
<select onselect="checkSelect(this)" id="slct">
<option selected="selected" value="default">select your country</option>
<option>egypt</option>
<option>usa</option>
</select>
</td>
<td><span id="errorslct"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
</table>
</form>
<script>
function allvalidate() {
validate();
checkAge(txtage);
checkuser(txtuser);
checkSelect(this);
}
function validate() {
var txtf = document.getElementById('txtfname');
if (txtf.value == 0 || txtf.value == null) {
document.getElementById('error').innerText = ('you must enter firstname');
document.getElementById('error').style.color = 'red';
txtf.focus();
return false;
}
else {
document.getElementById('error').innerText = ('');
//return true;
}
}
function checkAge(input) {
if (input.value < 18 || input.value > 70) {
document.getElementById('errorage').innerText = ('age must be from 18 :70');
document.getElementById('errorage').style.color = 'red';
return false;
}
else {
document.getElementById('errorage').innerText = ('');
return true;
}
}
function checkuser(input) {
var pattern = '^[a-zA-Z]+$';
if (input.value.match(pattern)) {
document.getElementById('erroruser').innerText = '';
return true;
}
else {
document.getElementById('erroruser').innerText = ('enter valid email');
document.getElementById('erroruser').style.color = 'red';
return false;
}
}
function checkSelect() {
var select=document.getElementById('slct')
if (select.value=='default') {
document.getElementById('errorslct').innerText = ('you must choose country');
document.getElementById('errorslct').style.color = 'red';
return false;
}
else {
document.getElementById('errorslct').innerText = '';
return true;
}
}
</script>
</body>
</html>
Change
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
To:
<td><input type="submit" value="register" onclick="return allvalidate()" /></td>
Otherwise the boolean value is discarded. You also need to change allvalidate to actually return false if one of the validations fail:
function allvalidate() {
var validated = true;
if (!validate()) validated = false;
if (!checkAge(txtage)) validated = false;
if (!checkuser(txtuser)) validated = false;
if (!checkSelect(this)) validated = false;
return validated;
}
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
well, I'm not expert but what I think is that data is not sending, you need to call the function on onsubmit event, instead of calling it on onclick event. It would send the data as well.

How can I debug this validation error when I cannot seem to reproduce it?

I built a sign up form on my website that has been (seemingly) randomly erroring for about 3% of my users (just an estimate). The error disallows the user from signing up for my service, and they often have to call the office so that we can manually add them as a new customer. This costs us quite a bit of time on the phone, and potentially costs us business for those users that decide not to call in, and instead go to a competitor.
I have tried debugging this many times, and even rebuilt the sign up system this past year out of frustration, but I am still encountering the bug. I just don't have any more ideas on how to debug it, and was hoping someone had an idea about a new way to test why this might be happening (or force the error to happen for me), or a better way of handling it.
*I tried to trim down my code to just include the relevant pieces (they are long files), so please let me know if there is something else I need to include
EDIT: #Greg Watters suggested that I write shared functions which multiple 'blur' handlers can use to manage the state for multiple inputs (like student password and confirm student password). I will be trying that next, but if anyone else has additional ideas, I am all ears. UPDATE This has no change on the issue
EDIT2 I created an email which allows me to see which inputs are marked as "invalid" right after the user clicks submit on the form, but prior to actual button firing. The inputs that were marked "invalid" were seemingly random
EDIT 3 A friend suggested that it might be an autofill issue. Because I have triggered the validation with a blur event, and the autocomplete may not trigger this event. I have added redundant validation on the submission button to check if this may fix the problem
How the sign up form and validation work
All required inputs start with a class of "invalid"
When a user fills in the input, I validate it using js, and if everything is okay, I remove the class "invalid". If it is not validated, I display an error below the input, highlight the input in red, and keep the class "invalid"
Once the user presses "submit", I loop through every input on the form and check for a class of "invalid". If any input still contains the class "invalid", I display a message to fix the errors at the bottom of the form and highlight the relevant inputs in red. If no inputs contain the class "invalid", the form submits.
What happens during the error
User fills out each required input, and no validation errors appear. When I speak with them on the phone live during this process, every single person is positive they have filled out the form with valid information and have filled in all required inputs
User clicks submit, and an error appears at the bottom of the form asking them to fix errors, but no inputs are highlighted red, and no extra input errors are displayed.
Form Validation
$("#signUp-submit").live("click", function() {
$(".signUpError").empty();
var error = false;
$(".signUpTextbox").each(function() {
if($(this).hasClass("invalid")) {
$(".signUpError").text('Please correct errors');
$(".invalid").css("background-color", "#ffcccc");
$('html, body').animate({scrollTop:575}, 'slow');
error = true;
return false;
}
});
if (error == false) {
var customerType = $("#signUp-customerType").val();
var school = $("#signUp-school").val();
var studentEmail = $("#signUp-studentEmail").val();
var studentFirstName = $("#signUp-studentFirstName").val();
var studentLastName = $("#signUp-studentLastName").val();
var studentPhone = $("#signUp-studentPhone").val();
var studentPhoneCarrier = $("#signUp-studentPhoneCarrier").val();
var studentAddress1 = $("#signUp-studentAddress1").val();
var studentAddress2 = $("#signUp-studentAddress2").val();
var parentEmail = $("#signUp-parentEmail").val();
var parentAddress1 = $("#signUp-parentAddress1").val();
var parentAddress2 = $("#signUp-parentAddress2").val();
var parentCity = $("#signUp-parentCity").val();
var parentState = $("#signUp-parentState").val();
var parentZip = $("#signUp-parentZip").val();
var parentPhone = $("#signUp-parentPhone").val();
var referral = $("#signUp-referral").val();
if (customerType == "student") {
var studentPassword = $("#signUp-studentPassword").val();
}
else if (customerType == "parent") {
var parentPassword = $("#signUp-parentPassword").val();
var parentFirstName = $("#signUp-parentFirstName").val();
var parentLastName = $("#signUp-parentLastName").val();
}
$(".footerSignUpContent").html('<div class = "loadingAnimationFooter" id = "loadingAnimation-FooterSignUp"></div>');
$.post(
'ajax/signUp.php',
{
'customerType': customerType,
'school': school,
'studentEmail': studentEmail,
'studentPassword': studentPassword,
'studentFirstName': studentFirstName,
'studentLastName': studentLastName,
'studentPhone': studentPhone,
'studentPhoneCarrier': studentPhoneCarrier,
'studentAddress1': studentAddress1,
'studentAddress2': studentAddress2,
'parentAddress1': parentAddress1,
'parentAddress2': parentAddress2,
'parentCity': parentCity,
'parentState': parentState,
'parentZip': parentZip,
'parentPassword': parentPassword,
'parentFirstName': parentFirstName,
'parentLastName': parentLastName,
'parentEmail': parentEmail,
'parentPhone': parentPhone,
'referral': referral
},
function (response) {
$("#footerTitle-SignUp").html("Thanks!");
$(".footerSignUpContent").html(response);
}
);
}
})
Individual input validations
$("#signUp-studentEmail").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var studentEmail = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentEmail != "") {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())) {
$(this).closest("tbody").find(".errorPlaceholder").text("Please enter a valid email");
$(this).css("background-color", "#ffcccc");
}
else {
$.post(
'ajax/signUpValidateEmail.php',
{
'email': studentEmail
},
function (response) {
$("#signUp-studentEmail").closest("tbody").find(".errorPlaceholder").html(response);
var notValid = $("#signUpValidateEmail").val();
if (notValid == 0) {
$("#signUp-studentEmailRepeat").addClass("invalid");
$("#signUp-studentEmailRepeat").closest("tbody").find(".errorPlaceholder").empty();
$("#signUp-studentEmailRepeat").css("background-color", "white");
var studentEmailRepeat = $("#signUp-studentEmailRepeat").val();
if (studentEmail != studentEmailRepeat) {
$("#signUp-studentEmailRepeat").closest("tbody").find(".errorPlaceholder").text("Emails do not match");
$("#signUp-studentEmailRepeat").css("background-color", "#ffcccc");
}
else {
$("#signUp-studentEmailRepeat").removeClass("invalid");
}
$("#signUp-studentEmail").removeClass("invalid");
}
else {
$("#signUp-studentEmail").css("background-color", "#ffcccc");
}
}
);
}
}
else {
$("#signUp-studentEmail").css("background-color", "#ffcccc");
}
});
$("#signUp-studentEmailRepeat").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var studentEmailRepeat = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentEmailRepeat != "") {
var studentEmail = $("#signUp-studentEmail").val();
if (studentEmail != studentEmailRepeat) {
$(this).closest("tbody").find(".errorPlaceholder").text("Emails do not match");
$(this).css("background-color", "#ffcccc");
}
else {
$(this).removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentEmail").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var parentEmail = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentEmail != "") {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())) {
$(this).closest("tbody").find(".errorPlaceholder").text("Please enter a valid email");
$("#signUp-parentEmail").css("background-color", "#ffcccc");
}
else {
$("#signUp-parentEmailRepeat").addClass("invalid");
$("#signUp-parentEmailRepeat").closest("tbody").find(".errorPlaceholder").empty();
$("#signUp-parentEmailRepeat").css("background-color", "white");
var parentEmailRepeat = $("#signUp-parentEmailRepeat").val();
if (parentEmail != parentEmailRepeat) {
$("#signUp-parentEmailRepeat").closest("tbody").find(".errorPlaceholder").text("Emails do not match");
$("#signUp-parentEmailRepeat").css("background-color", "#ffcccc");
}
$(this).removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentEmailRepeat").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var parentEmailRepeat = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentEmailRepeat != "") {
var parentEmail = $("#signUp-parentEmail").val();
if (parentEmail != parentEmailRepeat) {
$(this).closest("tbody").find(".errorPlaceholder").text("Emails do not match");
$(this).css("background-color", "#ffcccc");
}
else {
$(this).removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-studentFirstName").live("blur", function() {
var studentFirstName = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentFirstName != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-studentLastName").live("blur", function() {
var studentLastName = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentLastName != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-studentPhone").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var studentPhone = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentPhone != "") {
var phoneReg = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(!phoneReg.test($(this).val())) {
$(this).closest("tbody").find(".errorPlaceholder").text("Please enter a valid phone number");
$(this).css("background-color", "#ffcccc");
}
else {
$(this).removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-studentAddress1").live("blur", function() {
var studentAddress = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentAddress != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentAddress1").live("blur", function() {
var parentAddress1 = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentAddress1 != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentCity").live("blur", function() {
var parentCity = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentCity != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentState").live("blur", function() {
var parentState = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentState != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentZip").live("blur", function() {
var parentZip = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentZip != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-studentPassword").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var studentPassword = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentPassword != "") {
var passwordReg = /^.*(?=.{8,})(?=.*[a-zA-Z]).*$/;
if(!passwordReg.test($(this).val())) {
$(this).closest("tbody").find(".errorPlaceholder").text("Password must be at least 8 characters");
$(this).css("background-color", "#ffcccc");
}
else {
$("#signUp-studentPasswordRepeat").addClass("invalid");
$("#signUp-studentPasswordRepeat").closest("tbody").find(".errorPlaceholder").empty();
$("#signUp-studentPasswordRepeat").css("background-color", "white");
var studentPasswordRepeat = $("#signUp-studentPasswordRepeat").val();
if (studentPassword != studentPasswordRepeat) {
$("#signUp-studentPasswordRepeat").closest("tbody").find(".errorPlaceholder").text("Passwords do not match");
$("#signUp-studentPasswordRepeat").css("background-color", "#ffcccc");
}
$(this).removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-studentPasswordRepeat").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var studentPasswordRepeat = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(studentPasswordRepeat != "") {
var studentPassword = $("#signUp-studentPassword").val();
if (studentPassword != studentPasswordRepeat) {
$(this).closest("tbody").find(".errorPlaceholder").text("Passwords do not match");
$(this).css("background-color", "#ffcccc");
}
else {
$("#signUp-studentPasswordRepeat").removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentPassword").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var parentPassword = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentPassword != "") {
var passwordReg = /^.*(?=.{8,})(?=.*[a-zA-Z]).*$/;
if(!passwordReg.test($(this).val())) {
$(this).closest("tbody").find(".errorPlaceholder").text("Password must be at least 8 characters");
$(this).css("background-color", "#ffcccc");
}
else {
$(this).removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentPasswordRepeat").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var parentPasswordRepeat = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentPasswordRepeat != "") {
var parentPassword = $("#signUp-parentPassword").val();
if (parentPassword != parentPasswordRepeat) {
$(this).closest("tbody").find(".errorPlaceholder").text("Passwords do not match");
$(this).css("background-color", "#ffcccc");
}
else {
$("#signUp-parentPasswordRepeat").addClass("invalid");
$("#signUp-parentPasswordRepeat").closest("tbody").find(".errorPlaceholder").empty();
$("#signUp-parentPasswordRepeat").css("background-color", "white");
var parentPasswordRepeat = $("#signUp-parentPasswordRepeat").val();
if (parentPassword != parentPasswordRepeat) {
$("#signUp-parentPasswordRepeat").closest("tbody").find(".errorPlaceholder").text("Passwords do not match");
$("#signUp-parentPasswordRepeat").css("background-color", "#ffcccc");
}
$("#signUp-parentPasswordRepeat").removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentFirstName").live("blur", function() {
var parentFirstName = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentFirstName != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentLastName").live("blur", function() {
var parentLastName = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentLastName != "") {
$(this).removeClass("invalid");
}
else {
$(this).css("background-color", "#ffcccc");
}
});
$("#signUp-parentPhone").live("blur", function() {
$(this).closest("tbody").find(".errorPlaceholder").empty();
var parentPhone = $(this).val();
$(this).addClass("invalid");
$(this).css("background-color", "white");
if(parentPhone != "") {
var phoneReg = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(!phoneReg.test($(this).val())) {
$(this).closest("tbody").find(".errorPlaceholder").text("Please enter a valid phone number");
$(this).css("background-color", "#ffcccc");
}
else {
$(this).removeClass("invalid");
}
}
else {
$(this).css("background-color", "#ffcccc");
}
});
HTML of form
<table class="signUpTable">
<tbody>
<tr>
<td class="signUpTextboxTitle">Email*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-studentEmail" placeholder="student email">
</td>
</tr>
<tr>
<td></td>
<td class="errorPlaceholder"></td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Repeat Email*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-studentEmailRepeat" placeholder="repeat email">
</td>
</tr>
<tr>
<td></td>
<td class="errorPlaceholder"></td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Password*</td>
<td class="signUpTextboxCell">
<input type="password" class="invalid signUpTextbox" id="signUp-studentPassword" placeholder="password">
</td>
</tr>
<tr>
<td></td>
<td class="errorPlaceholder"></td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Repeat Password*</td>
<td class="signUpTextboxCell">
<input type="password" class="invalid signUpTextbox" id="signUp-studentPasswordRepeat" placeholder="repeat password">
</td>
</tr>
<tr>
<td></td>
<td class="errorPlaceholder"></td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">First Name*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-studentFirstName" placeholder="first name">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Last Name*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-studentLastName" placeholder="last name">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Cell Phone*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-studentPhone" placeholder="cell phone">
</td>
</tr>
<tr>
<td></td>
<td class="errorPlaceholder"></td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Phone Carrier</td>
<td class="signUpTextboxCell">
<input type="text" class="signUpTextbox" id="signUp-studentPhoneCarrier" placeholder="phone carrier">
</td>
</tr>
</tbody>
<tr>
<td colspan="2"><hr></hr></td>
</tr>
<tbody>
<tr>
<td colspan="2" class="signUpInstructions">Your local address must be within the city of <?php echo $footerLocation; ?>
</td>
</tr>
<tr>
<td class="signUpTextboxTitle">Student Address*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-studentAddress1" placeholder="student address 1">
<br />
<input type="text" class="signUpTextbox" id="signUp-studentAddress2" placeholder="student address 2">
</td>
</tr>
</tbody>
<tr>
<td colspan="2"><hr></hr></td>
</tr>
<tbody>
<tr>
<td class="signUpTextboxTitle">Parent Email*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-parentEmail" placeholder="parent email">
</td>
</tr>
<tr>
<td></td>
<td class="errorPlaceholder"></td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Repeat Email*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-parentEmailRepeat" placeholder="repeat parent email">
</td>
</tr>
<tr>
<td></td>
<td class="errorPlaceholder"></td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Permanent or Parent Address*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-parentAddress1" placeholder="parent address 1">
<br />
<input type="text" class="signUpTextbox" id="signUp-parentAddress2" placeholder="parent address 2">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">City*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-parentCity" placeholder="city">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">State*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-parentState" placeholder="state">
</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="signUpTextboxTitle">Zip*</td>
<td class="signUpTextboxCell">
<input type="text" class="invalid signUpTextbox" id="signUp-parentZip" placeholder="zip">
</td>
</tr>
<tr>
<td colspan="2" class="signUpInstructions">Parents use their own email address and password to login to a linked account. We will email them details.</td>
</tr>
</tbody>
<tr>
<td colspan="2"><hr></hr></td>
</tr>
<tbody>
<tr>
<td class="signUpTextboxTitle">How did you head about us?</td>
<td class="signUpTextboxCell">
<input type="text" class="signUpTextbox" id="signUp-referral" placeholder="referral">
</td>
</tr>
</tbody>
<tr>
<td colspan="2"><hr></hr></td>
</tr>
<tr>
<td class="signUpInstructions">*required</td>
</tr>
<tr>
<td colspan="2"><input type = "submit" class = "toolbarButton footerMiddleAlignRight" id = "signUp-submit" value = "Sign Up"></td>
</tr>
<tr>
<td colspan="2" class="signUpError"></td>
</tr>
<tr>
<td colspan="2"><input type = "text" class = "hiddenInput" id = "signUp-customerType" value = "<?php echo $customerType; ?>"></td>
</tr>
<tr>
<td colspan="2"><input type = "text" class = "hiddenInput" id = "signUp-school" value = "<?php echo $school; ?>"></td>
</tr>
</table>
Here's a hypothesis: most of the blur handlers remove the invalid class from their elements "immediately" (i.e., synchronously within the event handler). But there's one that doesn't: the #signUp-studentEmail handler launches a POST request and only removes invalid in the AJAX success function. If the user clicks Sign Up quickly after editing their email address (before that AJAX completes), the order of events may look like this:
click handler runs, sees invalid on the email textbox, reports the error.
AJAX completes, clears invalid from the textbox.
Thus the user would see an error, but no textboxes would be red.
If you can't reproduce this simply by editing the email field last and then clicking Sign Up, it may help to add a delay to the AJAX - either by delaying its launch with setTimeout, or by adding a delay to signUpValidateEmail.php on the server.

Form Validation with password match

I have two forms inside my body:
<body>
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validate();" />
</td>
</tr>
</table>
</form>
</body>
I would like to do the following:
For each form, validate to ensure it's filled in and also for the second form I want to validate that the two password matched. I have the following:
$( document ).ready(function() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
$('#cpass').blur(function(){
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
}
else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validate() {
if (t != null && y != null && k != null && j != null) {
}
if (t == "" || y == "" || k == "" || j == "") {
alert("fill in");
}
}
I preferred not to mix native JavaScript and validated using pure jQuery only. One of the benefits here is that the empty field check would work for any <form> since it's not tied to any particular form, input name or ids.
$( document ).ready(function() {
$( 'form' ).submit(function(event) {
var $form = $( this );
var checkPass = true;
$form.find( 'input' ).each(function( i, e) {
if (e.value.length === 0) {
event.preventDefault();
alert(e.name + " cannot be empty");
return (checkPass = false);
}
});
if( checkPass && $form.is( '[name="register"]' ) ) {
if( $form.find( '#pass').val() !== $form.find( '#cpass' ).val()) {
event.preventDefault();
alert( 'Passwords do not match.' );
}
}
});
});
Working Demo at JsFiddle.net
Basics:
If you want to check if a variable is not null, ideally, you should use !== & not !=.
If you want to check if a variable is "", ideally, you should use === and not ==.
Check out: http://www.w3schools.com/js/js_comparisons.asp
Use JSFiddle.net to give a better working example of your code WHICH can help others see a demo of your actual code.
Your code currently has lot of scope for optimization. Since its just a basic validation you are trying to achieve, why do you need to use jQuery? Why not just use JavaScript basic variable comparisons?
Google before you ask here. If its so straightforward, your question will get downvoted.
Alert is not the best way to notify the user to fill in. For example, your 'Password Matches' or 'Password Doesn't Match' div is a much better way to notify the user. Use Form Events to validate the form as the user is already filling in the details in the form!
Question responsibly by giving your exact problems and not just pasting the code! How would we know where you are facing a problem.
Variables work in Scope. Check the scope of variable before using them in different functions. For example, you define var t, y, k, j in first function and use it in second function - will throw up an error of undefined variable t.
From what information you provided, here's what I could help with:
HTML:
<form method=post name="signin">
<table>
<theader>Sign In</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 maxlength=25 name=em id=em />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 maxlength=15 name=up id=up />
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onclick="javascript:validateSignin()" />
</td>
</tr>
</table>
</form>
<br>
<br>
<br>
<br>
<form method=post name="register">
<table>
<theader>Don't have an account? Register, it's Free!</theader>
<tr>
<td>Email:</td>
<td>
<input type=text length=25 name=email id=email /><span id="nameerror"></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type=password length=15 name=pass id=pass />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td>
<input type=password length=15 name=cpass id=cpass /><span id="pwerror"></span>
</td>
</tr>
<tr>
<td>Account Type:</td>
<td>
<select id="seltype">
<option name=standard SELECTED>Standard</option>
<option name=admin>Administrator</option>
</td>
</tr>
<tr>
<td colspan=2>
<input type=button value="submit" onClick="JavaScript:validateRegister();" />
</td>
</tr>
</table>
</form>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#cpass').blur(function () {
if (k != j) {
document.getElementById("pwerror").innerHTML = "Password does not match";
} else {
document.getElementById("pwerror").innerHTML = "Password matches";
}
});
});
function validateRegister() {
var t = document.getElementById("email").value;
var y = document.getElementById("seltype").value;
var k = document.getElementById("pass").value;
var j = document.getElementById("cpass").value;
if (t !== null && y !== null && k !== null && j !== null) {}
if (t === "" || y === "" || k === "" || j === "") {
alert("fill in");
}
}
function validateSignin() {
var se= document.getElementById("em").value;
var sp= document.getElementById("up").value;
if (se !== null && sp !== null){ }
if (se === "" || sp === "") {
alert("fill in");
}
}
</script>
Hope it helps! :)

Categories