I would like to display an error message when a user types a value in an input field (emailaddressVal) that matches a value in my array (invalidEmailAddresses). But I don't know how to go about it.
Thanks for your help!
$(document).ready(function(){
$("input[name='emailAddress']").blur(function(){
// Actual Email Validation function
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var hasError = false;
var emailaddressVal = $("input[name='emailAddress']").val();
var invalidEmailAddresses =
['aol.com', 'yahoo.com', 'yahoo.fr', 'juno.com', 'hotmail.com', 'gmail.com'];
if($.inArray(invalidEmailAddresses,emailaddressVal) == -1) {
alert('The email provided is not from a business related domain');
}
});
});
Try the following code
$(document).ready(function () {
$("input[name='emailAddress']").blur(function () {
var emailAddress = $("input[name='emailAddress']").val().trim();
if (isValidEmailAddres(emailAddress)) {
var hasError = false;
var emailaddressVal = emailAddress.split('#').slice(1)[0].trim();
var invalidEmailAddresses = ['aol.com', 'yahoo.com', 'yahoo.fr', 'juno.com', 'hotmail.com', 'gmail.com'];
if ($.inArray(emailaddressVal, invalidEmailAddresses) >=0) {
alert('The email provided is not from a business related domain');
}
} else alert("Invalid EmailID");
});
function isValidEmailAddres(emailID) {
var regexExp = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return regexExp.test(emailID);
}
});
See this fiddle
Changes That I did
I added a email Validation Function. Only if it is a valid email address you will proceed for hostname checking.
Correct Format of $.inArray is $.inArray( stringvalue, array). So it has to be $.inArray(emailaddressVal,invalidEmailAddresses)
emailaddressVal will contain a full email address. First you need to extract the hostname from that full email address. It is done at
var emailaddressVal = emailAddress.split('#').slice(1)[0].trim();
So if your email address is abc#gmail.com, the above line will return gmail.com.
Return type of $inArray is the position at which the passed string (emailaddressVal in your case) is present in the arraylist (invalidEmailAddresses). It will return a value greater than or equal to 0. As per your requirement you have to show the message when you want the host in email id is present in array of host names. You need to do
if($.inArray(emailaddressVal, invalidEmailAddresses) >=0)
You can use the jQuery inArray test like this.
var emailaddressVal = $("input[name='emailAddress']").val();
The code beloe test the user input to see if it is in the array and stores the index in which it is located.
var inArrTest = $.inArray(emailaddressVal, invalidEmailAddresses);
This code test the inArrTest variable and gets the index of the users matched value.
if (inArrTest) {
// Your error message would go here. //
console.log(invalidEmailAddresses[inArrTest]);
}
You can nest your error message inside the if block.
The original code does not work because the -1 checks to see if the variable is not in the array.
$.inArray(invalidEmailAddresses,emailaddressVal) == -1)
Sukanya's code check to see if the variable is greater than 0 which is the first index of an array.
$.inArray(emailaddressVal,invalidEmailAddresses) > 0
Related
<script>
async function loadData() {
var data = await fetch("Product.xml");
var parsedData = await data.text();
var parser = new DOMParser();
var Product_document = parser.parseFromString(parsedData,"text/xml");
var results = "";
var AlertBox = ""
var user_id_input = document.getElementById("user_id").value;
var todos = Product_document.getElementsByTagName("product");
for(var i = 0; i < todos.length; i++) {
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
var Code = todos[i].getElementsByTagName("Code")[0].childNodes[0].nodeValue;
var Quantity = todos[i].getElementsByTagName("Quantity")[0].childNodes[0].nodeValue;
var Description = todos[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue;
var Price = todos[i].getElementsByTagName("Price")[0].childNodes[0].nodeValue;
if(user_id_input === Code) {
results = "<div>"
+ "Code: " + Code
+ ",<br/> Name: " + Name
+ ", <br/>Quantity: " + Quantity
+ ",<br/> Description " + Description
+ ",<br/> Price " + Price
+ "</div><br/>";
AlertBox= "True";
}
if(AlertBox !== "True") {
alert("Error");
}
}
document.getElementById("results").innerHTML = results;
}
</script>
I'm trying to code a web app that takes user input, parses an XML file and then displays some information. I have that part working.
My problem is, I want there to be an Error alert if the Input does not match any of the XML elements. I have coded one in, but for every element the app checks that doesn't match the user input the app is giving me an error alert. And I have no idea how to solve it.
enter image description here
I've tried adding a variable that changes to true if the input matches and only allowing the alert to show up if that variable is false and I still get the Alert.
enter image description here
Based on your code I think the reason why it is not working is the nodeValue property as this returns null.
When called on an element tag (nodeType 1) nodeValue returns null. nodeValue will return the actual text content when it is called from a text element (nodeType 3). The 'Code' tag is of type element and has a child of type text therefore you don't get the desired text value. You can read more on nodeType here.
To get the correct result from nodeValue you need to call it like this:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].firstChild.nodeValue;.
As you want to get the text content from an element you can also use the following code instead:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].textContent;
The if condition should now also be executed correctly as long as the user_id_input variable has also the correct value. If the function loadData is executed before the user has entered values into the form fields, you need to execute the function when your form has been submitted. This way you can make sure that the user has entered values to all required fields. You can read more about HTML Forms and managing them via JavaScript here if needed.
I would also suggest to use let and const instead of var.
Additionally I think you would like to use your variable AlertBox as a boolean. If that is the case please use the boolean datatype in JavaScript. You can write it like this:
let AlertBox = false; or let AlertBox = true;
var x = document.getElementsByTagName('button');//return button array
//arrays
var entry_age = [];//age
var entry_relation = [];//relation
var entry_smoker = [];//smoker
//add button clicked
x[0].addEventListener("click", function(){
var age = document.getElementsByName("age")[0].value;//pull age from box
var relation = document.getElementsByName("rel")[0].value;//pull relation
let smoker = document.querySelector('[name=smoker').checked;
//check relation
if(relation === "")
{
alert("please select a realation");
}
//check to see if age < 0
if(age < 0 || age === " ")
{
alert("age not applicable");
}
//add data to arrays
entry_age.push(age);
entry_relation(relation);
entry_smoker(smoker);
alert(entry_age[0]);
});
x[1].addEventListener("click", function(){
var age = JSON.stringify(entry_age);
alert(entry_age[1]);
document.getElementbyClassName("debug").innerHTML = JSON.stringify(entry_relation);
document.getElementByClass("debug").innerHTML = JSON.stringfy(entry_smoker);
});
I'm trying to store a value in entry age dynamically and convert that to JSON and display it in a only thing is I can't get the data to store in the array, how do I get the array to work globally? At this point I'm pretty sure it's my array but do y'all see anything wrong with the JSON. For debugging purposes I used an alert with the array index and the one in the second function is coming up as unidentified It is to return to a pre tag with the class name of debug. You guys have really helped me out a lot with this project.
I've been searching around and all the answers I've seen will use something along the lines of $('form :input')$ to get all of the inputs. But I already have a reference to the form using $("form").submit() and I just need to grab a specific input field from the fieldname. I'm unsure of how to use $(this) with additional selectors to get the forms specific elements
So, how would I go about doing that.
Example of the bit of code I need to workout.
$('form').submit(function(){
var form = $(this)
var form_errors = array_of_errors
for(var fieldname in form_errors){
var errors = form_errors[fieldname]
var field = \\how to get this
\\ Something like $(form, 'input[name='+fieldname+']') maybe?
}
});
$(selector, context)
jQuery selectors can have a second argument, used to define their context.
$(`input[name=${fieldname}]`, form);
will do the trick.
This means that your selector will look only inside the element you have passed as context.
Documentation:
http://api.jquery.com/jquery/#jQuery-selector-context
$(context).find(selector)
An alternative could be to use find() in conjunction with the context:
$(form).find(`input[name=${fieldname}]`);
$('form').submit(function(){
var $form = $(this), // good naming practice to use $ to signify jQuery object
form_errors = validateForm(this); // semi-colon
var fields = Object.keys( form_errors );
for ( var i=0,n=fields.length; i<n; i++ ){
var field = fields[i],
errors = form_errors[field],
$field = $form.find('input[name=' + field + ']');
$field.applyErrorMarkup(errors); // whatever you plan to do with the field
}
});
// Pseudocode of one possible way to validate your form
function validateForm(frm){
var errors = {};
// BEGIN LOOP: <insert code to iterate over fields and validity checks>
var field = 'fieldname'; // placeholder
if( true /* error found */ ){
var err = errors[field];
var msg = 'new error message'; // should be the dynamic validity check error message (e.g., 'only numbers permitted')
errors[field] = err && [msg].concat( err ) || msg;
}
// END LOOP
return errors;
}
working on this, too. I've fixed the spelling and (i think) the bracket errors. Also fixed a couple errors I saw that stood out, but didn't get too far. I'm still stumped as to where to go with it next.
(function(){
// Variable initialization (DO NOT FIX ANY OF THE BELOW VAR's)
var resultsDIV = document.getElementById("results"),
searchInput = document.forms[0].search,
currentSearch = ''
;
// Validates search query
var validate = function(query){
// Trim whitespace from start and end of search query
while (query.charAt[0] === " "){
query = query.substring(1, query.length);
};
while (query.charAt(query.length-1) === ""){
query = query.substring(0, query.length - 1);
};
// Check search length, must have 3 characters
if (query.length < 3){
alert ("Your search query is too small, try again.");
// (DO NOT FIX THE LINE DIRECTLY BELOW)
searchInput.focus();
return;
};
search (query);
};
// Finds search matches
var search = function (query){
// split the user's search query string into an array
var queryArray = query.join(" ");
// array to store matched results from database.js
var results = [];
// loop through each index of db array
for(var i=0, j=db.length; i<j; i++){
// each db[i] is a single video item, each title ends with a pipe "|"
// save a lowercase variable of the video title
var dbTitleEnd = db[i].indexOf('|');
var dbitem = db[i].tolowercase().substring(0, dbTitleEnd);
// loop through the user's search query words
// save a lowercase variable of the search keyword
for(var ii=0, jj=queryArray.length; ii<jj; ii++){
var qitem = queryArray[ii].tolowercase();
// is the keyword anywhere in the video title?
// If a match is found, push full db[i] into results array
var compare = dbitem.indexOf(qitem);
if(compare !== -1){
results.push(db[i]);
};
};
};
};
results.sort();
// Check that matches were found, and run output functions
if(results.length = );{
noMatch();
}else{
showMatches(results);
};
// Put "No Results" message into page (DO NOT FIX THE HTML VAR NOR THE innerHTML)
var noMatch = function(){
var html = ''+
'<p>No Results found.</p>'+
'<p style="font-size:10px;">Try searching for "JavaScript". Just an idea.</p>'
;
resultsDIV.innerHTML = html;
};
// Put matches into page as paragraphs with anchors
var showMatches = function(results){
// THE NEXT 4 LINES ARE CORRECT.
var html = '<p>Results</p>',
title,
url
;
// loop through all the results search() function
for(var i=0, j=results.length; i<j; i++){
// title of video ends with pipe
// pull the title's string using index numbers
titleEnd = results[i].indexOf('|');
title = results[i].subString(0, titleEnd);
// pull the video url after the title
url = results[i].substring(results[i].indexOf('|')+1, results[i].length);
// make the video link - THE NEXT LINE IS CORRECT.
html += '<p><a href=' + url + '>' + title + '</a></p>';
};
resultsDIV.innerHTML = html; //THIS LINE IS CORRECT.
};
// The onsubmit event will be reviewed in upcoming Course Material.
// THE LINE DIRECTLY BELOW IS CORRECT
document.forms[0].onsubmit = function(){
var query = searchInput.value;
validqte(query);
// return false is needed for most events - this will be reviewed in upcoming course material
// THE LINE DIRECTLY BELOW IS CORRECT
return false;
;
})();
There are a few syntax errors which should prevent this from running at all.
// syntax error
var results = ();
// should be
var results = [];
Also it appears that the definition of showMatches ends with an unmatched right parenthesis.
Given that somehow the code is running with these syntax errors (and possibly others I didn't notice), the (a) glaring issue is:
if (results.length = 0) {
Yeah, that's an assignment, not a comparison. You just set the array's length to zero, which effectively clears it. This both fails the length test here (returning 0), then hands the now empty array off to be displayed as results, but of course it's now an array of length 0.
On another note, probably not an actual problem but I can't help it. The while loop business to trim the string? Yeah, don't do that. Use trim. If you need a polyfill there's always:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
currently i am using
var email, fax, sms = false;
if($('#uemail:checked').val() != undefined)
email = true;
if($('#ufax:checked').val() != undefined)
fax = true;
if($('#usms:checked').val() != undefined)
sms = true;
but its such a long way to write it.
is there a better way to write this?
Try this:
if($('#uemail').is(':checked'))
email = true;
Or even shorter:
email = $('#uemail').is(':checked');
You're passing the :checked selector into jQuery's .is() method which returns a boolean value;
http://api.jquery.com/is/
You can use .length, like this:
var email = $('#uemail:checked').length,
fax = $('#ufax:checked').length,
sms = $('#usms:checked').length;
.length is the length of the array of matched elements...if it's not checked, it's 0. And since .length == 0 serves for .length == false in JavaScript you can do the short version above. If you need a true/false, then just do .length != 0 instead :)
Or, another alternative that produces booleans, just use the DOM .checked property:
var email = $('#uemail')[0].checked,
fax = $('#ufax')[0].checked,
sms = $('#usms')[0].checked;
Or, no jQuery at all just use getElementById():
var email = document.getElementById('uemail').checked,
fax = document.getElementById('ufax').checked,
sms = document.getElementById('usms').checked;
An alternative may be to use an associative array and then loop through the keys. It would certainly be more DRY.
// Initialise all the checkbox values as unknown
var items = {
"email" : none,
"fax" : none,
"sms" : none
};
// Loop through each checkbox index
for (var index in items) {
// Get the id of the checkbox
var id = '#u' + index;
// Find out if the checkbox is checked
items[index] = $(id).is(':checked');
}