multiple validation error for a textbox using jquery - javascript

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(', '));

Related

Do I have a problem with my javascript or is it something else?

(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.

Uncaught TypeError: Cannot read property 'value' of undefined contact form html

I'v made a contact form in HTML, The code that was written is supposed to if the form is filled out correctly, change the button from "submit enquiry" to "processing..."
The code works when I test it using dreamweaver but when i try it on wordpress using the DIVI theme im getting errors
function change()
{
var salutation = document.forms["testform"]["salutation"];
var firstname = document.forms["testform"]["firstname"];
var lastname = document.forms["testform"]["lastname"];
var email = document.forms["testform"]["email"];
var phone = document.forms["testform"]["phone"];
var address = document.forms["testform"]["address1"];
var state = document.forms["testform"]["state"];
var zipcode = document.forms["testform"]["zipcode"];
var comments = document.forms["testform"]["comments"];
var custentity_stiltz_where_did_you_hear = document.forms["testform"]
["custentity_stiltz_where_did_you_hear"];
if (salutation.value == "")
{
window.alert("fill in")
salutation.focus()
return false;
}
if (firstname.value == "")
{
return false;
}
if (lastname.value == "")
{
return false;
}
if (email.value == "")
{
return false;
}
if (phone.value == "")
{
return false;
}
if (address.value == "")
{
return false;
}
if (state.value == "")
{
return false;
}
if (zipcode.value == "")
{
return false;
}
if (comments.value == "")
{
return false;
}
if (custentity_stiltz_where_did_you_hear.value == "")
{
return false;
}
var elem = document.getElementById("buttonscriptcpf");
if (elem.value=="Submit Enquiry") elem.value = "Processing...";
else elem.value = "Submit Enquiry";
return true;
}
Uncaught TypeError: Cannot read property 'value' of undefined

JavaScript. Please advise on better code reuse and/or structure

As the title suggests, A better coding structure or implementation for my JavaScript below. This checks a ID element values from a form before submitting to a database.
I'm interested to know if I could have reduced the code size/could have implemented reuse of code which will give me some tips for the future!
Thanks.
function validateRunnerID()
{
var runnerID = document.getElementById('RunnerID').value;
if (isNaN(runnerID) || runnerID < 1 || runnerID > 9999)
{
return "RunnerID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateEventID()
{
var eventID = document.getElementById('EventID').value;
if (isNaN(eventID) || eventID < 1 || eventID > 9999)
{
return "EventID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateDate()
{
var checkDate= /^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/;
var date= document.getElementById('Date');
var tof= date.value.match(checkDate);
return tof? "" : "Date: Enter a Valid Date with parameters: YYYY-MM-DD \n\n";
}
function validateFinishTime()
{
var finishTime = document.getElementById("FinishTime").value;
if (finishTime.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/))
{
return ""
}else{
return "Finish Time: Enter a valid Time with parameters: HH:MM:SS \n\n";
}
}
//
//
function validatePosition()
{
var position = document.getElementById('Position').value;
if (position.length == 0)
{
document.getElementById('Position').value = -1;
return "";
}else{
return "";
}
}
function validateCategoryID()
{
var categoryID = document.getElementById('CategoryID').value;
if (categoryID.length == 0)
{
document.getElementById('CategoryID').value = -1;
return "";
}else{
return "";
}
}
function validateAgeGrade()
{
var ageGrade = document.getElementById('AgeGrade').value;
if (ageGrade.length == 0)
{
document.getElementById('AgeGrade').value = -1;
return "";
}else{
return "";
}
}
function validatePB()
{
var pBest = document.getElementById('PB').value;
if (pBest.length == 0)
{
document.getElementById('PB').value = 0;
return "";
}else{
return "";
}
}
//
//
function validateForm()
{
var result = validateRunnerID() + validateEventID() + validateDate() + validateFinishTime() + validatePosition() + validateCategoryID() + validateAgeGrade() + validatePB();
if ( result == "" )
{
alert("Data Accepted and Submitted \n\n");
return true;
}else{
alert("Please Fix Errors Listed: \n\n" + result);
return false;
}
}
One thing you can do is to accept an elementId as input to your validation functions. This allows to reuse the same logic for different fields.
For example:
function validate4DigitInt(elementId)
{
var value = document.getElementById(elementId).value;
if (isNaN(value) || value < 1 || value > 9999)
{
return elementId + ": Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
Now you can validate both RunnerId and EventId using the same function:
var result="";
result+=validate4DigitInt("RunnerId");
result+=validate4DigitInt("EventId");

Onblur returns wrong data

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);
});
})

Applying multiple select filters on a table in jQuery

I have three select boxes which filter the table on with different criteria. For example, if a user wants to see records with Medium priorities, a Yes On Air Critical & Closed Status. Closed is a data-attribute for every row.
I can do that but my issue is if user wants to select a single filter again, it just shows blank result. Here's the javascript:
$("#input_filter_priority").change(function() {
var data = this.value.split(" ");
var $tr_row = $('#project_table').find("tr:not(.hidden)");
var priority_column = $('#project_table').find("tr :not(.hidden) td:nth-child(5)");
if (this.value == "") {
$tr_row.show();
return;
}
$tr_row.hide();
if (filtered_row !== null) {
filtered_row = filtered_row.filter(function() {
$r = $(this);
if ($r.is(":contains('" + data + "')")) {
return true;
}
return false;
})
.show();
} else {
filtered_row = $tr_row.filter(function() {
$tr_text = $(this).val();
$r = $(this);
if ($r.is(":contains('" + data + "')")) {
return true;
}
return false;
})
.show();
}
});
$("#input_closed_filter").change(function() {
var data = this.value.split(" ");
var $tr_row = $('#project_table').find("tr:not(.hidden)");
if (this.value == "") {
$tr_row.show();
return;
}
$tr_row.hide();
if (filtered_row !== null) {
filtered_row = filtered_row.filter(function() {
$r = $(this);
if ($(this).attr('data-closed').match(data)) {
return true;
}
return false;
})
.show();
} else {
filtered_row = $tr_row.filter(function() {
$tr_text = $(this).val();
if ($(this).attr('data-closed').match(data)) {
return true;
}
return false;
})
.show();
}
});
$("#input_on_air_filter").change(function() {
var data = this.value.split(" ");
var $tr_row = $('#project_table').find("tr ");
var on_air_column = $('#project_table').find("tr td:nth-child(6)");
if (this.value == "") {
$tr_row.show();
return;
}
$tr_row.hide();
if (filtered_row !== null) {
filtered_row = filtered_row.filter(function() {
$r = $(this);
if ($(this).attr('data-critical').match(data)) {
return true;
}
return false;
})
.show();
} else {
filtered_row = $tr_row.filter(function() {
$tr_text = $(this).val();
$r = $(this);
if ($(this).attr('data-critical').match(data)) {
return true;
}
return false;
})
.show();
}
});
What should I do here in case user selects same filter twice or any number of times (Suppose if he changes his mind).
Here's the related JSBin.
Here is a simplified/working version:
var priorityFilterData=null;
var onAirCriticalFilterData=null;
var closedFilterData=null;
function applyFilters(){
var $tr_row = $('#project_table').find("tr");
$tr_row.hide();//hide all rows by default
//Show only the rows that meet each filter condition
$tr_row.filter(function(){
var closedFilterCondition = (closedFilterData === null || $(this).attr('data-closed').match(closedFilterData));
var onAirFilterCondition = (onAirCriticalFilterData === null || $(this).attr('data-critical').match(onAirCriticalFilterData));
var priorityFilterCondition = (priorityFilterData === null || $(this).is(":contains('" + priorityFilterData + "')"));
return closedFilterCondition && onAirFilterCondition && priorityFilterCondition;
}).show();
}
$("#input_closed_filter").change(function() {
closedFilterData = this.value.split(" ");
applyFilters();
});
$("#input_on_air_filter").change(function() {
onAirCriticalFilterData = this.value.split(" ");
applyFilters();
});
$("#input_filter_priority").change(function() {
priorityFilterData = this.value.split(" ");
applyFilters();
});

Categories