I did my form validation first and it worked.However, after i include my other functions in my javascript file, it stops working. I try to check all the functions but i couldnt find where did i do wrong. Im still new to javascript so thank you in advance for those that took their time to fix my problem.
var gErrorMsg = "";
function validateForm() {
"use strict";
var isAllOK = false;
gErrorMsg = "";
var fnameOK = FName();
var lnameOK = LName();
var emailOK = Email();
var addOK = Address()
var cityOk = City();
var pnOK = PN();
if (fnameOK && lnameOK && emailOK && addOK && cityOk && pnOK) {
isAllOK = true;
}
else {
alert(gErrorMsg);
gErrorMsg = "";
isAllOK = false;
}
return isAllOK;
}
function FName() {
var owner = document.getElementById("name").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((owner.length == 0)) {
gErrorMsg = gErrorMsg + "Your first name cannot blank**\n"
nameOk = false;
}
else {
if (!pattern.test(owner)) {
gErrorMsg = gErrorMsg + "Your first name must only contain alpha characters**\n"
nameOk = false;
}
}
return nameOk;
}
function LName() {
var owner = document.getElementById("Lname").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((owner.length == 0)) {
gErrorMsg = gErrorMsg + "Your last name cannot blank**\n"
nameOk = false;
}
else {
if (!pattern.test(owner)) {
gErrorMsg = gErrorMsg + "Your last name must only contain alpha characters**\n"
nameOk = false;
}
}
return nameOk;
}
function Email() {
var email = document.getElementById("email");
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email.value)) {
result = true;
}
else { //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address **\n"
}
return result;
}
function Address() {
var add = document.getElementById("address").value;
var addOk = true;
if ((add.length == 0)) {
gErrorMsg = gErrorMsg + "Your address cannot blank**\n"
addOk = false;
}
return addOk;
}
function City() {
var city = document.getElementById("city").value;
var pattern = /^[a-zA-Z ]+$/
var cityOk = true;
if ((city.length == 0)) {
gErrorMsg = gErrorMsg + "Please state the city you are form**\n"
cityOk = false;
}
else {
if (!pattern.test(city)) {
gErrorMsg = gErrorMsg + "Your city name must only contain alpha characters**\n"
cityOk = false;
}
}
return cityOk;
}
function PN() {
var pn = document.getElementById("phone").value;
var pnOk = true;
var pattern = /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
if ((pn.length == 0)) {
gErrorMsg = gErrorMsg + "Please state your contact number**\n"
pnOk = false;
}
else {
if (!pattern.test(pn)) {
gErrorMsg = gErrorMsg + "Your contact number should only has 10 numbers*\n"
pnOk = false;
}
}
return pnOk;
}
function storeitem(item_id) {
sessionStorage.setItem("item_id", item_id);
window.location.replace("enquiry.html");
}
function displayitem() {
document.getElementById("sbj").value = "RE: Enquiry on " + sessionStorage.getItem("item_id");
}
function validateForm() {
var product = document.getElementById("type").value;
sessionStorage.product = product;
return result;
}
//Store individual product page into sessionStorage
function storeProduct(productName) {
var options = ["Runway", "Commercial", "Fitness", "Fashion"];
options.forEach(array);
function array(value) {
if (value == productName) {
sessionStorage.productIndex = options.indexOf(value);
}
}
}
//Fill the subject field with the value of product
function storeSub() {
document.getElementById("type").selectedIndex = sessionStorage.productIndex;
var product = document.getElementById("type").value;
sessionStorage.subject = product;
document.getElementById("subject").value = sessionStorage.subject;
}
//Storing first optgroup into array
function productlist1() {
var select = document.getElementById("type");
var options = ["Runway", "Commercial", "Fitness", "Fashion"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
//change the value of the session storage according to the new product selected by user
function change() {
var product = document.getElementById("type").value;
sessionStorage.product = product;
document.getElementById("subject").value = sessionStorage.product;
}
//if validateForm returns returns false nothing will be sent to the server
function init() {
var regForm = document.getElementById("form");
//Lecture 7 - following 2 calls register inputs elements to respond to onblur and onclick events.
//registerInputsOnBlur();
//registerInputsOnClick();
regForm.onsubmit = validateForm;
displayitem()
}
window.onload = init;
Related
(I would like to adress that English is not my first language)
I have this problem with javascript for a very long time and I don't know what to do.
This javascript is for a registration. Sometimes it gives access even though I haven't typed everything, or it doesn't give access even though I have typed everything correctly
If someone can help thanks already!
function validateform() {
var res = true;
res = userNameVal() && res;
res = passowrdVal() && res;
res = ConfirmPhone() && res;
res = emailConfirm() && res;
res = Name() && res;
res = lastName() && res;
res = city() && res;
return res;
}
function Name() {
var firstName = document.getElementById("firstName").value;
var msgBox = document.getElementById("NameMsg");
if (firstName.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (reg.test(firstName) && reg1.test(firstName) && reg2.test(firstName) && (English(firstName))) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function lastName() {
var LastName = document.getElementById("LastName").value;
var msgBox = document.getElementById("LastNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (Name.length == 0) {
msgBox.innerHTML = "You must enter your name";
return false;
}
if (reg.test(LastName) || reg1.test(LastName) || reg2.test(LastName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function city() {
var CityName = document.getElementById("CityName").value;
var msgBox = document.getElementById("CityNameMsg");
var reg = /[0-9]/;
var reg1 = /\w/;
var reg2 = /\s/;
if (CityName.length == 0) {
msgBox.innerHTML = "You must enter your City";
return false;
}
if (reg.test(CityName) || reg1.test(CityName) || reg2.test(CityName)) {
msgBox.innerHTML = "Your name can't have a number, space or a special char";
return false;
}
msgBox.innerHTML = "";
return true;
}
function userNameVal() {
var userName = document.getElementById("userName").value;
var msgBox = document.getElementById("userNameMsg");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter a username";
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "Your username must start with a letter";
return false;
}
msgBox.innerHTML = "";
return true;
}
function passowrdVal() {
var pass = document.getElementById("password").value;
var msgBox = document.getElementById("passwordMsg");
var specialChar = /[#!#$%^&*()-+]/;
if (pass.length == 0) {
msgBox = "You must enter a password";
return false;
}
if (pass.length < 7) {
msgBox.innerHTML = "The password must contain at least 7 charactes"
return false;
}
if (!specialChar.test(pass)) {
msgBox.innerHTML = "password must contain one special letter ";
return false;
}
msgBox.innerHTML = "";
return true;
}
function ConfirmPhone() {
var phone = document.getElementById("phone").value;
var msgBox = document.getElementById("phoneMsg");
var reg = /^0{1}(2|3|4|6|8|9|5[0|[2-8]|73)-?[1-9]\d{6}$/;
if (!reg.test(phone)) {
msgBox.innerHTML = "Phone number is illegal";
return false;
}
msgBox.innerHTML = "";
return true;
}
function emailConfirm() {
var email = document.getElementById("email").value;
var msgBox = document.getElementById("emailMsg");
var reg = /^\w+/;
if (!reg.text(email)) {
msgBox.innerHTML = "Mail can hava only one following letter";
return false;
}
msgBox.innerHTML = "";
reg = /^\w+([\.-]?\w+)*#\w+/;
if (!reg.test(email)) {
msgBox.innerHTML = "Mail must have #";
return false;
}
reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!reg.test(email)) {
msgBox.innerHTML = "invalid email";
return false;
}
msgBox.innerHTML = "";
return true;
}
function isLetter(ch) {
if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"))
return true;
return false;
}
function isDigit(ch) {
if (ch >= "0" && ch <= "9")
true;
false;
}
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
We need more information about exactly what happens in your success and failure cases. However I see potential issues here:
For me, this function does not work for two reasons:
function English(str) {
i = 0;
while (str[i].isLetter) {
i++;
}
if (i == str.length())
return true;
return false;
}
First, the variable i is not declared, do you mean this:
let i = 0
Possibly, i is declared globally, and so you are inadvertently trashing another value? Generally using let is preferable to using var, you can have other unexpected effects on globals if you use var.
Second, I don't see how this is working. For me str[i].isLetter is not defined.
while (str[i].isLetter) {
Do you intend to use your isLetter() function
isLetter(str[i])
If that doesn't help you will need to explain in more detail what happens in your failure cases.
Can someone please tell me how to add my below JavaScript (function validateEmail() to the JavaScript I already created (function validateForm()? I need to combine the 2 into one. What I did was create a JavaScript to create error messages, then my new one creates an error message if the Email field was typed incorrectly. The longer JavaScript is what needs the shorter one. Do I just add an else if, if than? I am new to JavaScript. Thank you for those that help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
if (email == "") {
emailError.innerHTML = "Please enter your Email";
ret = false;
}
else {
emailError.innerHTML = "";
}
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
NEW JAVASCRIPT
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
return valid;
}
Your final function should look like below:
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
}
else {
nameError.innerHTML = "";
}
ret &= validateEmail();
var phone = document.forms["contactform"]["telephone"].value;
var phoneError = document.getElementById('telephone.error');
if (phone == "") {
phoneError.innerHTML = "Please enter your telephone";
ret = false;
}
else {
phoneError.innerHTML = "";
}
return ret;
}
// in diff file
function validateEmail() {
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid) {
emailError.innerHTML = "Please enter a valid email address";
}
else {
emailError.innerHTML = "";
}
return valid;
}
EDIT
If you can not (or dont want to) change validateForm function to include call to validateEmail then you can specify both functions in the form onsubmit
onsubmit="return validateForm() && validateEmail()"
Your form validation script simply needs to call your additional function as an additional test.
Try adding this to the end of your main function:
if(!validateEmail()) {
// error code
ret=false;
}
else {
// ok
}
return ret;
My form check does not work. If I leave alias field empty it returns name field as filled.
var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';
function checkIt() {
if (alias.value != '') {
document.getElementById("alias").style.borderColor = "#3c763d";
return true;
} else {
document.getElementById("alias").style.borderColor = "#a94442";
status = false;
}
if (name.value != '') {
document.getElementById("name").style.borderColor = "#3c763d";
return true;
} else {
document.getElementById("name").style.borderColor = "#a94442";
status = false;
}
}
name.onblur=checkIt;
alias.onblur=checkIt;
Try this, you should use current object this instead of global variable when eventing firing
var alias = document.getElementById("alias");
var name = document.getElementById("name");
var status = '';
function checkIt() {
if (this.value != '') {
this.style.borderColor = "#3c763d";
status = true;
} else {
this.style.borderColor = "#a94442";
status = false;
}
}
name.onblur=checkIt;
alias.onblur=checkIt;
JSFIDDLE DEMO
Try this one:
Plain Js
script
var validate = function(e) {
var v = this.value;
this.style.borderColor = ('' !== v) ? '#3c763d' : '#a94442';
};
document.getElementById('alias').onblur = validate;
document.getElementById('name').onblur = validate;
JQuery
script
$(function(){
$("#alias, #name").on('focusout', function() {
var box = $(this);
var c = ('' !== box.val()) ? '#3c763d' : '#a94442';
box.css('border-color', c);
});
})
I want to print specific emty error message as well as number error message for the age field while during the button click. for my code only the last error message is diplaying.
This is for Validation Purpose.
<script type="text/javascript">
$(document).ready(function () {
$("#<%=btnSubmit.ClientID %>").click(function () {
var error = 0;
var name = $('#<%=txtName.ClientID%>').val();
if ($.trim(name) == '') {
$('#name_error_msg').text('Name cannot be Empty');
$('#name_error_msg').parent().show();
error = 1;
} else
$('#name_error_msg').text('');
var country = $('#<%=ddlCountry.ClientID%>').val();
if (country == 0) {
$('#country_error_msg').text('Please select the Country');
$('#country_error_msg').parent().show();
error = 1;
}
else
$('#country_error_msg').text('');
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
else
$('#age_error_msg').text('');
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!filter.test(emailReg)) {
$('#email_error_msg').text('Invalid email format');
$('#email_error_msg').parent().show();
error = 1;
}
else {
$('#email_error_msg').text('');
}
var email = $('#<%=txtEmail.ClientID%>').val();
if ($.trim(email) == '') {
$('#email_error_msg').text('Email cannot be Empty');
$('#email_error_msg').parent().show();
error = 1;
} else {
$('#email_error_msg').text('');
}
if (!($('#<%=ChkAgree.ClientID%>').is(':checked'))) {
error = 1;
$('#check_error_msg').html("Please Tick the Agree to Terms of Use.");
$('#check_error_msg').parent().show();
}
else
$('#check_error_msg').html(" ");
if (error) {
return false;
} else {
return true;
}
});
});
</script>
All you need to do is, replace:
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
}
else
$('#age_error_msg').text('');
with:
var filter = /^[0-9-+]+$/;
var age = $('#<%=txtAge.ClientID%>').val();
if ( $.trim(age) == '' || !filter.test(age)) {
$('#age_error_msg').text('Invalid Age');
$('#age_error_msg').parent().show();
error = 1;
} else {
$('#age_error_msg').text('');
}
You could create a temp variable to add up each error.
var age_errors = [];
var age = $('#<%=txtAge.ClientID%>').val();
if ($.trim(age) == '') {
age_errors.push('Age is empty');
$('#age_error_msg').parent().show();
error = 1;
}
var filter = /^[0-9-+]+$/;
if (!filter.test(age)) {
age_errors.push('Invalid Age number');
$('#age_error_msg').parent().show();
error = 1;
}
// set the error: empty string or a comma-separated list.
$('#age_error_msg').text(age_errors.join(', '));
I have the function
function validateEmailp() {
var two = document.getElementById('email').value;
var first = two.split("#")[1];
var badEmails = ["gmail.com", "yahoo.com"]
if (badEmails.indexOf(first) != -1) {
document.getElementById("email").value = "";
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
return false;
}
return true;
}
HTML is
<input id="email" onblur="validateEmailp()"><div id="emailerrorz"></div>
After the user types in the input field a free e-mail he will get that error (we do not..)
But after he rectify the email to a non-free e-mail the error should clear up. How do i do that with javascript?
function validateEmailp() {
var two = document.getElementById('email').value;
var first = two.split("#")[1];
var badEmails = ["gmail.com", "yahoo.com"]
if (badEmails.indexOf(first) > -1) {
document.getElementById("email").value = "";
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
return false;
}
document.getElementById('emailerrorz').innerText = ''
return true;
}
Make an else case:
if (badEmails.indexOf(first) != -1) {
document.getElementById("email").value = "";
document.getElementById('emailerrorz').innerText = 'We do not accept free e-mails'
return false;
} else {
document.getElementById('emailerrorz').innerText = ""; // clear error
}