I need help with simplifying/making shorter of the following validation code.
Help would be greatly appreciated.
At the moment there's too much text, my teacher said it could be done easier/cleaner...
I'm really stuck.
Thank you.
window.addEventListener('load',init,false);
function init(){
var submit = document.getElementById("submit");
var gender = document.getElementById("gender");
var age = document.getElementById("age");
var length = document.getElementById("length");
var weight = document.getElementById("weight");
var duration = document.getElementById("duration");
var time = document.getElementById("time");
submit.addEventListener('click', validation, false);
gender.addEventListener('checked',validategender,false);
age.addEventListener('blur', validateage, false);
length.addEventListener('blur',validatelength,false);
weight.addEventListener('blur',validateweight,false);
duration.addEventListener('blur',validateduration,false);
time.addEventListener('checked',validatetime,false);
}
function validategender(){
var man = document.getElementById("man");
var vrouw = document.getElementById("vrouw");
var genderfout = document.getElementById("genderFout");
if(man.checked != true && vrouw.checked !=true){
genderfout.innerHTML = "Please choose a gender";
return false;
}else {
genderfout.innerHTML = "";
}return true;
}
function validateage() {
var age = parseInt(document.getElementById("age").value, 10);
var ageFout = document.getElementById("ageFout");
if (isNaN(age) || age < 0 || age > 130) {
ageFout.innerHTML = "Please enter a valid age";
return false;
} else {
ageFout.innerHTML = "";
}
return true;
}
function validateweight() {
var weight = parseInt(document.getElementById("weight").value, 10);
var weightFout = document.getElementById("weightFout");
if (isNaN(weight) || weight < 30 || weight > 200) {
weightFout.innerHTML = "Please enter a valid weight";
return false;
} else {
weightFout.innerHTML = "";
}
return true;
}
function validatelength() {
var length = parseInt(document.getElementById("length").value, 10);
var lengthFout = document.getElementById("lengthFout");
if (isNaN(length) || length < 50 || length > 220) {
lengthFout.innerHTML = "Please enter a valid length";
return false;
} else {
lengthFout.innerHTML = "";
}
return true;
}
function validateduration() {
var duration = parseInt(document.getElementById("duration").value, 10);
var durationFout = document.getElementById("durationFout");
if (isNaN(duration) || duration < 0) {
durationFout.innerHTML = "Please enter a valid time-duration";
return false;
} else {
durationFout.innerHTML = "";
}
return true;
}
function validatetime(){
var minutes = document.getElementById("minutes");
var hours = document.getElementById("hours");
var timeFout = document.getElementById("timeFout");
if(minuten.checked !=true && uur.checked !=true){
timeFout.innerHTML = "choose a time unit!";
return false;
}else {
timeFout.innerHTML = "";
}
return true;
}
function validation(e){
var genderOk = validategender();
var ageOk = validateage();
var weightOk = validateweight();
var lengthOk = validatelength();
var durationOk = validateduration();
var timeOk = validatetime();
if (!genderOk || !ageOk || !weightOk || !lengthOk || !durationOk || !timeOk){
e.preventDefault();
}
}
if JQuery not allowed that leave another option
Regular expression
you can validate but needs a little reading
Use a JQuery validator
http://docs.jquery.com/Plugins/Validation
Your validation code will be reduced to half of what it is now or possibly much less.
Related
Having trouble with a combined file of html, CSS and javascript that is giving me an undisclosed error, used JSLint to check for errors but the only errors I were given were 'Line is longer than 80 characters', 'use spaces not tabs' and 'unexpected var'. Could someone please give me some help I'm real stuck.
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html"
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = function() {validate()};
var cancel = document.getElementById("cancel");
cancel.onclick = function cancelBooking()
}
window.onload = init;
it's common rule of eslint, if you want to ignore these error on you code, you can use eslint-disable on top of your js code
/* eslint-disable */
alert('foo');
The problem is inside your init() function. I have corrected it please try using this. You were calling the function cancelBooking() like this function cancelBooking() which was giving error.
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = function() {validate()};
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking()
}
I have used SweetAlert for showing alerts of validation and the code is below however its not working properly only in firefox. The alertbox starts appearing and then disappears and Javascript is bascially hung from that point. The code is as follows:
jQuery('.enroll-button').click(function (e) {
e.preventDefault();
var l = Ladda.create(this);
var tLeadType = jQuery('input[name="radioOpt"]:checked', '#sellBuyOpt').val()
var nSourceId = 0;
<?php if (isset($_GET["nsourceid"])){
echo 'nSourceId = '.$_GET["nsourceid"];
} ?>
var inputElements = [];
var tFirstName = jQuery("#firstName");
var tLastName = jQuery("#lastName");
var tEmailAddress = jQuery("#email");
var tCity = jQuery("#city");
var tState = jQuery("#state");
var tPhoneNumber = jQuery("#phoneNumber");
inputElements.push(tFirstName);
inputElements.push(tLastName);
inputElements.push(tEmailAddress);
inputElements.push(tCity);
inputElements.push(tState);
inputElements.push(tPhoneNumber);
//validations
var validated = true;
for(var i= 0; i < inputElements.length; i++){
if(inputElements[i].val().trim()===""){
inputElements[i].val("");
inputElements[i].attr("placeholder","This is required");
inputElements[i].css("border-color","#A33643");
validated = false;
}
if(i == 2){
var res = validateEmail(inputElements[i].val());
if(!res){
inputElements[i].val("");
inputElements[i].attr("placeholder","Valid Email required");
inputElements[i].css("border-color","#A33643");
validated = false;
}
}
if(i == 4 && inputElements[i].val() == "Select a state"){
sweetAlert("Oops...", "Please select a valid state!", "error");
validated = false;
}
if(i == 5 && !simpleClientPhoneValidator(inputElements[i].val())){
inputElements[i].val("");
inputElements[i].attr("placeholder","Invalid Phone Number");
inputElements[i].css("border-color","#A33643");
validated = false;
}
I have used the following javascript code to add inline error in my form. I want to error to be removed after the error is corrected after each field is corrected. I have created a single function for all the validations, so not able to use else and remove the error manually.
var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/
var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,}$/;
function validateForm() {
var x = document.forms["LoginForm"]["email"];
if (x.value == "") {
x.value = "";
document.getElementById('pointemail').innerHTML = "Please enter the email id.";
x.focus();
return false;
} else if (!emailpattern.test(x.value)) {
x.value = "";
document.getElementById('pointemail').innerHTML = "Please enter a valid email address.";
x.focus();
return false;
}
x = document.forms["LoginForm"]["password"];
if (x.value == "") {
x.value = "";
document.getElementById('pointpassword').innerHTML = "Please enter the password.";
x.focus();
return false;
} else if (!passwordpattern.test(x.value)) {
x.value = "";
document.getElementById('pointpassword').innerHTML = "Password should have minimum 8 characters, one upper case, one lower case and one special character";
x.focus();
return false;
}
}
Try This
var emailpattern = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})$/
var passwordpattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&]{8,}$/;
function validateForm() {
var x = document.forms["LoginForm"]["email"];
document.getElementById('pointemail').innerHTML = "";
document.getElementById('pointpassword').innerHTML = "";
//Add your if else here.
}
Hope it will be useful. :)
Provide an extra else statement after elseif
else {
document.getElementById('pointemail').innerHTML = '';
}
Similarly for pointPassword
i have a form with javascript validation. there are 3 drop-down(select) fields with questions and 3 input fields with answers.
is there any way to validate the select fields so that they don't have the same question?
here is my code
<script type="text/javascript">
var errmsg;
function validate()
{
var textA= document.getElementById("text1");
var textB= document.getElementById("text2");
var textC = document.getElementById("text3");
var textD = document.getElementById("text4");
var textE = document.getElementById("text5");
var textF = document.getElementById("text6");
var txt1 = document.getElementById("text1").value;
var txt2 = document.getElementById("text2").value;
var txt3 = document.getElementById("text3").value;
var txt4 = document.getElementById("text4").value;
var txt5 = document.getElementById("text5").value;
var txt6 = document.getElementById("text6").value;
var txt1_len = txt1.length;
var txt2_len = txt2.length;
var txt3_len = txt3.length;
var txt4_len = txt4.length;
var txt5_len = txt5.length;
var txt6_len = txt6.length;
if(txt1_len == '')
{
errmsg = "Please select a question";
document.getElementById("ermsg").innerHTML = errmsg;
textA.focus();
return false;
}
else if(txt2_len == 0 || txt2_len > 23 || txt2_len < 3)
{
errmsg = "Invalid Answer";
document.getElementById("ermsg").innerHTML = errmsg;
textB.focus();
return false;
}
else if(txt3_len == '')
{
errmsg = "Please select a question";
document.getElementById("ermsg").innerHTML = errmsg;
textC.focus();
return false;
}
else if(txt4_len == 0 || txt4_len > 23 || txt4_len < 3)
{
errmsg = "Invalid Answer";
document.getElementById("ermsg").innerHTML = errmsg;
textD.focus();
return false;
}
else if(txt5_len == '')
{
errmsg = "Please select a question";
document.getElementById("ermsg").innerHTML = errmsg;
textE.focus();
return false;
}
else if(txt6_len == 0 || txt6_len > 23 || txt6_len < 3)
{
errmsg = "Invalid Answer";
document.getElementById("ermsg").innerHTML = errmsg;
textF.focus();
return false;
}
else
{
return true;
}
return false;
}
</script>
and then the html code
https://jsfiddle.net/johnmathew21/ty999fkv/
you should compare the text inside each ddl ,
i add the following condition :
$('#text1 option:selected').text() === $('#text2 option:selected').text()
working fiddel : here
On change of 1st drop down - disable/remove that particular question from other drop downs.
$('#text1').change(function(){
$('#text2 option[value='+$('#text1').val() +']').attr('disabled',true);
$('#text3 option[value='+$('#text1').val() +']').attr('disabled',true);
});
something like this will work.
I have created a form that validates using JQuery and JavaScript. The only problem is, would be that it validates one field at a time. So the user has to correct the first field first and then press submit again to see if the next field is valid.
What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages.
Here is My JS:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength < 4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
return false;
}
else
{
return true;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
return false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
return false;
}
else
{
return true;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if (fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
return false;
}
else
{
return true;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if (lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
return false;
}
else
{
return true;
}
}
function validateForm()
{
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
}
And here is my submit form code:
$('#your-form').submit(validateForm);
Instead of returning true or false return a string containing the error and an empty string if no error was found.
Then validateForm could be something like
function validateForm()
{
error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
...
if(error === ""){
return true;
}
$("#ErrorLname").text(error);
return false;
}
Working Fiddle
var validate;
function validateUserName()
{
validate = true;
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
validate = false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
validate = false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
validate = false;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
validate = false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
validate = false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
validate = false;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
validate = false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
validate = false;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
validate = false;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
validate = false;
}
}
function validateForm()
{
validateUserName();
validatePassword();
validateEmail();
validateFirstName();
validateLastName();
return validate;
}
You need to access all the fields and check if the field is valid r not. If the field is valid skip it, otherwise put the field in an array. When all the fields have been checked, then display the error fields from the array all at one time.