Advanced Javascript form validation function - javascript

This is what I'm using.
It's great. I only need to add function that checks if one of "cp", "bp", "hp" input area is entered or not. If not it should give an error that says "Please enter at least 1 phone number."
(cp = cell phone, bp = business phone, hp = home phone)

function checkPhones(){
var frm = document.forms["myform"];
var cell = frm.cp.val;
var bus = frm.bp.val;
var home = frm.hp.val;
if(ValidatePhone(cell) || ValidatePhone(bus) || ValidatePhone(home)){
return true;
}
return false;
}
function ValidatePhone(val){
//insert code to check phone meets your system requirements
//either length or pattern
//return true or false
}
frmvalidator.setAddnlValidationFunction("checkPhones");

Related

with password validification javascript and html form

Im trying to code a simple task.
i need to get a password from html form, and check if there is both numbers and letters there, and that the password is not longer then 10 letters or short then 4.
so i wrote something (probably terrible) and its not working (surprisingly xD).
anyways, heres my code.
function checkpassword(checked_id, error_id, err_color){
var upperCaseLetters = /[A-Z]/g;
var lowerCaseLetters = /[a-z]/g;
var numbers = /[0-9]/g;
element_checked = document.getElementById(checked_id);
element_error = document.getElementById(error_id);
element_error.style.color = err_color;
if (!checked_id.value.match(upperCaseLetters) && !checked_id.value.match(lowerCaseLetters)) {
element_checked.style.backgroundColor = err_color;
element_error.innerHTML = "enter letters";
return false;
}
else if(!checked_id.value.match(numbers))
{
element_checked.style.backgroundColor = err_color;
element_error.innerHTML = "Enter numbers";
return false;
}
return true;
}
The primary issue is that you used checked_id.value, which should be element_checked.value.
Also, generally it's advisable to create variables with let instead of var if you don't need them to be global.

Matching user input with REGEX

Maybe the subject line is incorrect, but here is my question:
I am trying to see if the user input is a valid email address, or if there is an input at all at the first place. if none of the above, then i want to loop the question requesting the answer again, until i get a valid answer(in this case, email address). Below is the code i have written, which was working until i added REGEX testing.
function emailPrompt() {
var ui = SpreadsheetApp.getUi();
var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
var button = entry.getSelectedButton();
var response = entry.getResponseText();
var sum = 1;
for(var i=0;i<sum;i++){
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var matchRegex = regex.test(response);
if(response == ""||response == " "|| response != matchRegex) {
if(!matchRegex) { ui.alert("Invalid Email Address")}
ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
sum++;
} else {
sum--;
}
}
return response;
Logger.log(response);
}
Specifically, if the input is incorrect/invalid email address, i inserted another if statement to alert the user. I am positive i am messed the code somewhere in the REGEX matching/testing. Any help would be much appreciated. TIA
Your regex statement is ok. It tests and returns a boolean. Your first if statement is a little redundant. response == ""||response == " "|| response != matchRegex Most of these are already tested by the regex statement and the last one should never be false as you are comparing a string to a boolean.
EDIT: Additionally, the response variable is never update with the new prompt data (Code updated).
function emailPrompt() {
var ui = SpreadsheetApp.getUi();
var entry = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
var button = entry.getSelectedButton();
var response = entry.getResponseText();
var sum = 1;
for(var i=0;i<sum;i++){
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var matchRegex = regex.test(response);
if(!matchRegex) {
ui.alert("Invalid Email Address");
//Ask for email again and set new response.
var responseItem = ui.prompt("REQUIRED: Email Address", "Please type the email address you want the exported excel spreadsheet to be emailed to:"+"\n\n", ui.ButtonSet.OK);
response = responseItem.getResponseText();
sum++;
}
//sum--; this isn't needed to stop the loop.
if(sum > 3) //You shouldn't go on forever... Stop after a few tries?
break;
}
Logger.log(response); //Moved above return so this code runs.
return response;
}

How can I get my span id’s to display the appropriate messages when user doesn’t follow rules?

I am currently having problems with displaying different span error messages for some of the same input texboxes based on if the user doesn't follow my validation rules. I really could use some suggestions of how I can make some of my if statements better to enforce my rules that I have setup. I am okay with how my if statement is validating the username and how if statement is validating the password, but I have been struggling to try to figure what is the best method for validating my repeatemail textbox and emailaddress textbox. Can someone help me? Thanks in advance! Here is my HTML, CSS, and JavaScript/JQuery code
$('#button2').on('click', function () {
var NewUsernameError = document.getElementById("New_Username_error");
var NewPasswordError = document.getElementById("New_Password_error");
var NewEmailAddressError = document.getElementById("New_Email_error");
// var NewRepeatEmailAddressError=document.getElementById("NewReenter_Email_error");
// How can I get my span id's to display one of two different error //messages based on my rules below? Right now it will only display first error //messages. Do I need to create two different span ids (except for the password // texbox) for each input textbox or is one span id fine how I currently have //it? Shouldn't I be able to display either message just using one span id?
if($(".newUsername").val().length < 6)
{
NewUsernameError.innerHTML= "The username must be at least 6 characters";
// NewUsernameError.innerHTML= "There is an already existing account with username";
}else
{
NewUsernameError2.innerHTML = '';
}
if($(".newPassword").val().length < 6) {
{
NewPasswordError.innerHTML= "The password must be at least 6 characters";
}else{
NewPasswordError.innerHTML = '';
}
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
{
NewEmailAddressError.innerHTML= "The email must not be left empty.";
NewEmailAddressError.innerHTML= "The email must contain # symbol in it.";
}else{
NewEmailAddressError.innerHTML= '';
}
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
}else{
NewRepeatEmailAddressError.innerHTML= '';
}
.
Lots of problems here.
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
That tries to compare the <input> element instead of its contents.
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
That tries to compare undefined instead of the form element's contents. (jQuery doesn't use .value.)
Instead, you want .val():
if($(".newEmail").val() == "" && $(".newEmail").val() != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
...
if($(".repeatEmail").val() != $(".newEmail").val() && $(".repeatEmail").val() == ""){
A secondary problem is where you try to assign two error messages simultaneously:
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
In these cases the second .innerHTML is going to immediately overwrite the first one, so the first error message will never be seen. Each of those errors needs to be in its own, separate if {} condition.
Third, this isn't how to do regex comparisons, that regex contains several syntax errors (no trailing slash, mismatched parens), and even if it worked it would disallow many valid email addresses:
$(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
Better email address validation regexes can be found in e.g. this question, but even those can disallow some valid addresses. Keep things simple and test only for what the error message claims you're testing for, the presence of an # symbol:
/#/.test($('.newEmail').val())
Putting it all together
Cleaning your original function, converting all the vanilla js into jQuery (there's no real drawback to mixing them other than that it makes the code harder to read, but I figure if you've already got jQuery may as well use it), and rearranging some logic to simplify the code results in this:
var validate=function() {
// clear out the error display ahead of time:
var newUsernameError = $("#New_Username_error").html('');
var newPasswordError = $("#New_Password_error").html('');
var newEmailAddressError = $("#New_Email_error").html('');
var newRepeatEmailAddressError = $("#Repeat_Email_error").html('');
// just to make the later conditions easier to read, let's grab all the values into vars:
var newUsername = $('.newUsername').val();
var newPassword = $('.newPassword').val();
var newEmail = $('.newEmail').val();
var repeatEmail = $('.repeatEmail').val();
// presumably you'll want to prevent form submit if there are errors, so let's track that:
var errorsFound = false;
if (newUsername === "") {
errorsFound = true;
newUsernameError.html("The username must not be empty.");
} else if (newUsername.length < 6) {
errorsFound = true;
newUsernameError.html("The username must be at least 6 characters.");
}
if (newPassword.length < 6) {
errorsFound = true;
newPasswordError.html("The password must be at least 6 characters.");
}
if (newEmail === "") {
errorsFound = true;
newEmailAddressError.html("The email must not be left empty.");
} else if (!/#/.test(newEmail)) {
errorsFound = true;
newEmailAddressError.html("The email must contain an # symbol.");
}
if (repeatEmail !== newEmail) {
errorsFound = true;
newRepeatEmailAddressError.html("This repeat email doesn't equal to the first one entered.");
}
// No need to test for repeatEmail being empty, since that's already covered by the newEmail case above.
// OK, all conditions checked, now:
if (errorsFound) {
// prevent form submit. (If this is called in an onsubmit handler, just return false.)
} else {
// allow form submit.
}
console.log("Errors found: ", errorsFound);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username: <input class="newUsername">
<div id="New_Username_error"></div>
Password: <input class="newPassword">
<div id="New_Password_error"></div>
newEmail: <input class="newEmail">
<div id="New_Email_error"></div>
repeatEmail: <input class="repeatEmail">
<div id="Repeat_Email_error"></div>
</form>
<button onclick="validate()">Validate</button>
Keep one container for the errors you might expect to get on the input. I would do something like this to avoid all the else and else if's
$('#button2').on('click', function () {
// VALIDATE USERNAME
var newUserErrStr = '';
var newUsernameVal = $(".newUsername").val();
if(newUsernameVal.length < 6) newUserErrStr += "The username must be at least 6 characters";
document.getElementById("New_Username_error").innerHTML = newUserErrStr;
// VALIDATE PASSWORD
var newPasswordErrStr = '';
var newPasswordVal = $(".newPassword").val();
if(newPasswordVal.length < 6) newPasswordErrStr += "The password must be at least 6 characters";
document.getElementById("New_Password_error").innerHTML = newPasswordErrStr;
// VALIDATE EMAIL
var newEmailErrStr = '';
var newEmailVal = $(".newEmail").val();
if (newEmailVal === "") newEmailErrStr += "The email must not be left empty<br/>";
if (newEmailVal !== /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z]/ ) newEmailErrStr += "The email must contain # symbol in it.";
document.getElementById("New_Email_error").innerHTML = newEmailErrStr;
});

Javascript form validation for date not working

I have this javascript running on a html form. really struggling to get this working, Nothing pops up, no alerts at all. any help please. My code is probably terrible but I have only been using javascript for 4 weeks
function validate(form){
var vRunnerId = document.forms["submitrunnertime"]["RunnerId"].value;
var vEventId = document.forms["submitrunnertime"]["EventId"].value;
var vDate = document.forms["submitrunnertime"]["Date"].value;
var vFinishTime = document.forms["submitrunnertime"]["FinishTime"].value;
var vPosition = document.forms["submitrunnertime"]["Position"].value;
var vCategoryId = document.forms["submitrunnertime"]["CategoryId"].value;
var vAgeGrade = document.forms["submitrunnertime"]["AgeGrade"].value;
var vPB = document.forms["submitrunnertime"]["PB"].value;
var validFormat = /^\d{4}-\d{2}-\d{2}$/;
if (/\D/.test(vRunnerId)){
alert("Please only enter numeric characters only for your Runner ID");
return false;
}
if (/\D/.test(vEventId)){
alert("Please only enter numeric characters only for your Event ID");
return false;
}
if (!validFormat.test(vDate){
alert("Please enter date in YYYY-MM-DD");
return false;
}
return true;
}
I don't see your vDate being defined anywhere in that function, so it looks like you forgot to add that to your javascript.
You are grabbing the <input> value twice. Once here:
var vDate = document.forms["submitrunnertime"]["Date"].value;
and again in the check:
if (!validFormat.test(vDate.value)){
You're trying to find the .value of a .value which I would assumed would throw en error.

Adding function is disabling other functions in the js file

I had this function in a js file and everything was working just fine :
function check_acco_form()
{
var name=$("#name").val();
var institution=$("#institution").val();
var year=$("#year").val();
//PNR Data
var pnr1=$("#pnr1").val();
var pnr2=$("#pnr2").val();
// Arrival date info
var arr_year=$("#arr_year").val();
var arr_month=$("#arr_month").val();
var arr_date=$("#arr_date").val();
//Departure date info
var dep_year=$("#dep_year").val();
var dep_month=$("#dep_month").val();
var dep_date=$("#dep_date").val();
var numericExpression = /^[0-9]+$/;
//Name, institution and year must not be empty
if(name=="" || institution=="" || year=="")
{
alert("One or more fields are empty.");
return;
}
//PNR must be all numbers
if(!pnr1.match(numericExpression) || !pnr2.match(numericExpression))
{
alert("A PNR number consists of 10 digits only. Please enter again.");
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if(pnr1.length!=3 || pnr2.length!=7)
{
alert('Invalid PNR Number.');
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if((arr_month==dep_month && dep_date<arr_date) || (dep_month<arr_month))
{
alert('Invalid dates.Please check again.');
return;
}
//Test passed. Store in database;
URL="saveAcco.php";
parameters="name="+name+"&ins="+institution+"&year="+year+"&pnr="+pnr1+""+pnr2+"&dateArr="+arr_year+"-"+arr_month+"-"+arr_date+"&dateDep="+dep_year+"-"+dep_month+"-"+dep_date;
$.get(URL+"?"+parameters,function(data){
$("#msg_box").html(data);
if(data=="Your changes have been saved." || data=="Your data has been saved and is pending approval.")
{
$("#acco_status").html('<br/><b>Accomodation Approval Status</b> : <span style="padding:3px;background-color:#f4fb3c">Approval Pending</span><br/><br/>');
}
$("#msg_box").fadeIn("slow",function(){
setTimeout('fadeOutMsgBox();',3000);
});
});
}
I made a little changes to this function (added the variables 'mobile_num' and 'train_num', included 'if' conditions to make sure the user enters numbers only and made changes to the jQuery get function) that which resulted in the following code:
function check_acco_form()
{
//Personal Information
var name=$("#name").val();
var institution=$("#institution").val();
var year=$("#year").val();
//Contact Information
var mobile_num=$("#mobile").val();
//PNR Data
var pnr1=$("#pnr1").val();
var pnr2=$("#pnr2").val();
//Train Number
var train_num=$("#trainnum").val();
// Arrival date info
var arr_year=$("#arr_year").val();
var arr_month=$("#arr_month").val();
var arr_date=$("#arr_date").val();
//Departure date info
var dep_year=$("#dep_year").val();
var dep_month=$("#dep_month").val();
var dep_date=$("#dep_date").val();
var numericExpression = /^[0-9]+$/;
//Name, institution and year must not be empty.
if(name=="" || institution=="" || year=="")
{
alert("One or more fields are empty.");
return;
}
//PNR can be empty but if entered must be all numbers
if(pnr1!="" and pnr2!="")
{
if(!pnr1.match(numericExpression) || !pnr2.match(numericExpression))
{
alert("A PNR number consists of 10 digits only. Please enter again.");
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
if(pnr1.length!=3 || pnr2.length!=7)
{
alert('Invalid PNR Number.');
$("#pnr1").val("");
$("#pnr2").val("");
return;
}
}
//Train number can be empty but if entered must be all numbers
if(train_num!="")
{
if(!train_num.match(numericExpression))
{
alert("Train number must consits of digits only");
$("#trainnum").val("");
return;
}
}
//Mobile num can be empty but must be all numbers
if(mobile_num!="")
{
if(!mobile_num.match(numericExpression))
{
alert("Invalid mobile number");
$("#mobile_num").val("");
return;
}
if(mobile_num.length!=10)
{
alert('A mobile number consists of 10 digits.Please enter again.');
return;
}
}
if((arr_month==dep_month && dep_date<arr_date) || (dep_month<arr_month))
{
alert('Departure date cannot be before arrival date.Please check again.');
return;
}
//Test passed. Store in database;
URL="saveAcco.php";
parameters="name="+name+"&ins="+institution+"&year="+year+"&pnr="+pnr1+""+pnr2+"&dateArr="+arr_year+"-"+arr_month+"-"+arr_date+"&dateDep="+dep_year+"-"+dep_month+"-"+dep_date+"&mobile="+mobile_num+"&train_num="+train_num;
$.get(URL+"?"+parameters,function(data){
$("#msg_box").html(data);
if(data=="Your changes have been saved." || data=="Your data has been saved and is pending approval.")
{
$("#acco_status").html('<br/><b>Accomodation Approval Status</b> : <span style="padding:3px;background-color:#f4fb3c">Approval Pending</span><br/><br/>');
$("#acco_letter_print").html('Download accomodation letter here');
$("#acco_letter_print").fadeIn();
}
$("#msg_box").fadeIn("slow",function(){
setTimeout('fadeOutMsgBox();',3000);
});
}); //End of get function
}
After the changes, suddenly all functions in the js file of this function have stopped working including this function. On searching the forum , I found this discussion : JavaScript function causing all other functions not to work inside js file which says that the error may be due to use of reserved words. However , I can't find any reserved words used as variables in my code. Any ideas what may the problem?
You have this in there:
if(pnr1!="" and pnr2!="")
It should be:
if(pnr1!="" && pnr2!="")
Any syntactical errors like this will cause the entire thing to fail, be sure to check your error console for things like this, they'll quickly point out the cause.
As an aside, try not to pass a string to setTimeout() as well, pass the function reference directly, changing this:
setTimeout('fadeOutMsgBox();',3000);
To this:
setTimeout(fadeOutMsgBox,3000);
This will give less issues, and allow the function to be anywhere in scope, it doesn't have to be global (like it would with a string).

Categories

Resources