Changing a Labels value in Javascript after being passed into a function - javascript

I am trying to make a function for java script that evaluates the text within a form and updates a label next to the form with either Valid entry or Invalid entry.
I have the code working here so far
function validateText(form) {
if(form.value == '') {
document.getElementById("reasonLabel").innerHTML = "Invalid Entry";
return false;
}
else{document.getElementById("reasonLabel").innerHTML = "Invalid Entry";}
var re = /^[\w ]+$/;
if(!re.test(form.value)) {
document.getElementById("reasonLabel").innerHTML = "Invalid Entry";
return false;
}
document.getElementById("reasonLabel").innerHTML = "Valid Entry";
return true; }
However I want to use this function and apply it to all forms inside my html each form has a corresponding label next to it.
My question is how do I pass in a label and edit its value without using .getElementByID()
Sorry if this is an obvious question I am very new to javascript.

If you have the label (which had to have been gotten using document.getElementById() or something similar in the first place), you can use it as a normal variable, like in the following:
function validateText(form, label) {
if(form.value == '') {
label.innerHTML = "Invalid Entry";
return false;
}
else{
label.innerHTML = "Invalid Entry";
}
var re = /^[\w ]+$/;
if(!re.test(form.value)) {
label.innerHTML = "Invalid Entry";
return false;
}
label.innerHTML = "Valid Entry";
return true;
}
Then label could be gotten by passing something like document.getElementById("reasonLabel") into the function.

You can pass the label's DOM object (returned from getElementByID) as a parameter, just like any other value.

Related

basic javascript form validation - validate same input types with same function

I have always used jQuery validate() for forms, but have run into a problem recently after an upgrade to our XMPie software (we do targeted communications).
The new version of XMPie requires jQuery 1.10.2 which is a version not supported by validate(), so I'm doing the validation manually.
I can easily validate by writing a separate function for each input, but it means re-writing at least some of the code to target a specific input name or id for example.
What I'm wondering is why can't I write a generic function for a specific input type (for example a simple text field) and let the input call the function on focusout(), passing itself as a parameter?
If I've got two text inputs, "fullName" and "userName" why can't I use
$(document).ready(function () {
var inputName = "";
var inputValue = "";
var inputAlert = "";
$("input").focusout(function () {
inputIdentify(this);
console.log(inputName);
inputGetValue(this);
console.log(inputValue);
if (this.type == "text") {
console.log("YES");
textValidate(inputName, inputValue);
}
});
function inputIdentify(theInput) {
inputName = theInput["name"];
console.log(inputName);
return inputName;
}
function inputGetValue(theInput) {
inputValue = theInput["value"];
return inputValue;
}
function textValidate(theInput, inputValue) {
console.log(theInput,inputValue);
var letters = /^[A-Za-z ]+$/;
if (inputValue.match(letters)) {
$(theInput).addClass("correct");
return true;
} else {
$(theInput).removeClass("correct");
$(theInput).addClass("incorrect");
// alert('Username must have alphabet characters only');
$(inputName).focus();
return false;
}
}
});
to remove and add simple css classes (coloured border) to indicate the problem fields?
Thanks and regards,
Malcolm
You're not passing the correct arguments to textValidate(). You're passing inputName as the theInput, but textValidate() uses $(theInput) to access the input element. You should pass this as that argument:
textValidate(this, inputValue);
Also, your use of global variables is poor design. Since inputIdentify() and inputGetValue() return values, you should assign the returned value to local variables, instead of having those functions set global variables.
$("input").focusout(function () {
var inputName = inputIdentify(this);
console.log(inputName);
var inputValue = inputGetValue(this);
console.log(inputValue);
if (this.type == "text") {
console.log("YES");
textValidate(this, inputValue);
}
});
function inputIdentify(theInput) {
var inputName = theInput["name"];
console.log(inputName);
return inputName;
}
function inputGetValue(theInput) {
var inputValue = theInput["value"];
return inputValue;
}

html - use onsubmit and action together

I want the form to post the credentials via a get request but have difficulties making it work together with the onsubmit parameter which is used to validate the data entered. This is my form code:
<form onsubmit="return formValidation()" action="show_get.php" method="get" name="registration">
This is the code I used for validation
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
{
if (allLetter(name)) {
if (ValidateEmail(uemail)) {
if (checkDate()) {
}
}
}
return false;
}
}
function allLetter(name) {
var letters = /^[A-Za-z]+$/;
if (name.value.match(letters)) {
return true;
}
else {
alert('Name must have alphabet characters only');
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
}
}
If you attach an onsubmit event handler and it returns false, the form will not be submitted. In your case, that always happens, even if the input is valid.
You check allLetter(), then ValidateEmail() and checkDate(), but you don't return true when they're all valid. Your code continues and it reaches return false;. The submit event handler returns the result of that validation function (which is false), so it returns false too. This tells the form to not submit.
Change your validation function to this:
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
if (allLetter(name) && ValidateEmail(uemail) && checkDate()) {
return true;
} else {
return false;
}
}
If all three checks return true, the validation function will return true as well and the form will be submitted.
Note: You had one unnecessary pair of brackets ({}), I removed them. I also improved readability by combining all the nested if statements into one.
Edit: Also, your checkDate() doesn't return true and false accordingly. It returns undefined by default, which is a falsy value. This means that it won't pass the validation function's && check and the form won't get submitted. Change checkDate() to this:
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
} else {
return true;
}
}
Edit 2: You also incorrectly get the values of your input elements. When you do this:
var name = document.registration.name;
var uemail = document.registration.email;
You get the HTML element with name attribute name and HTML element with name attribute email. You should get the elements' values:
var name = document.registration.name.value;
var uemail = document.registration.email.value;
It's best to edit your answer and add the full HTML and JavaScript. There might be more problems.

Global variable setting fails in JavaScript validation

I am getting an error while setting global variable flag inside function.
Global variable declaration
var flag = false;
Function to validate textbox
//To validate Product Name field
function Name() {
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
flag = false;
}
else {
$('#productNameError').text('');
flag = true;
}
}
Function to validate quantity
//To validate Product Quantity Field
function Quantity() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
flag = true;
}
else {
$('#productQtyError').text('Enter Quantity of the Product');
flag = false;
}
}
else {
$('#productQtyError').text('Quantity is required');
flag = false;
}
}
//Validation Summary
function validate() {
if (flag == true) {
$('#validationSummary').text('');
return true;
}
else {
$('#validationSummary').text('Please fill out required fields.');
return false;
}
}
I am calling first two functions on onfocusout event of textbox and calling validate() function on button click. The problem which I am facing is: inside the Quantity() flag is not getting set to false. Although the field remains blank,record gets inserted.
if you are getting flag=true in validate() then you may be calling Quantity() first ,it will set flag false then Name() which will set flag to true so It bypassed validate() function.
This is not the correct way, you are trying to achive validation. Consider scenario, when user have entered the correct value in first filed, flag will be set to true with the fact that second field is empty amd form will be submitted and hold true vice versa.
If want to achive by this way, keep as many flag variables as the number of fields amd chech all those variable inside validate.
Or, use '.each' to iterate each element and validate it and keep appending validation mesages to dom object.
Thanks
Don't use Global Variables
You're going to have a bad time if you use global variables, you can use the revealing module pattern to encapsulate some of the messiness
Would suggest something like this :
var app = app || {};
app.product = app.product || {};
app.product.validate = app.product.validate || {};
app.product.validate.isValid = false;
app.product.validate.name = function(){
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
app.product.validation.flag = false;
} else {
$('#productNameError').text('');
app.product.validation.flag = true;
}
}
app.product.validate.quantity = function() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
app.product.validate.flag = true;
} else {
$('#productQtyError').text('Enter Quantity of the Product');
app.product.validate.flag = false;
}
} else {
$('#productQtyError').text('Quantity is required');
app.product.validate.flag = false;
}
}
console.log is Your Friend
Try putting a console.log inside some of those methods, what I am guessing your issue is is that something is being called out of the order you expect and setting the flag to a value you aren't expecting.
Can do console.log statement like this console.log if you open up your developer console should show you the output from the console

validating an email with javascript

I am learning about simple javascript form validation and I am just curious why my email validation is not working. I am trying to grab the information from the email input field and run my function with the RegEx in it. Any help would be appreciated.
fiddle demo: http://jsfiddle.net/6SWj4/
(function(){
var emailAddr = document.getElementById("f_email").value;
console.log(emailAddr);
// console.log(email.test(str));
//
// if(email.test(str) == true){
// console.log("true");
// }else{
// console.log("false");
// }
myform.onsubmit = function(e){
//Below is one example of the validateField call with an argument.
//You must dynamically retrieve the ID name from the DOM/HTML.
validateField(emailAddr); //id = is the form input field ID
e.preventDefault();
return false;
};
var validateField = function(inputName){
if (inputName.name === 'f_email'){
var pattern = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var emailVal = new RegExp(pattern);
//You will need to create an else-if statement for each input field id. The
// format will be similar to the above IF statement.
}else{
console.log("not valide");
}
var pass = emailVal.test(inputName);
console.log(pass);
var errorMsg = inputName.nextSibling.nextSibling.nextSibling.nextSibling;
if (!pass || inputName.value.length < 2){
errorMsg.style.display='block';
inputName.style.backgroundColor = 'red';
} else if (pass && inputName.value.length > 5){
errorMsg.style.display='none';
inputName.style.backgroundColor = 'green';
} else {
errorMsg.style.display='none';
inputName.style.backgroundColor = 'white';
};
};
})(); // end wrapper
Your problem stems from getting the value of the input on page load, not after user has entered anything. Try:
myform.onsubmit = function(e){
/* get value withing submit handler*/
var emailAddr = document.getElementById("f_email").value;
console.log(emailAddr);
//Below is one example of the validateField call with an argument.
//You must dynamically retrieve the ID name from the DOM/HTML.
validateField(emailAddr); //id = is the form input field ID
e.preventDefault();
return false;
};
ALso flaw in validateField(). Argument expected is inpuname but you are passing in email input value
You have many errors in the code. First what i said you on the comments, you have to do the document.getElementById("f_email").value; inside of onsubmit function. You are also declaring variables inside something and using it out of it, for example emailVal that you declare inside the if. That cannot work, you have to declare it before the if. check with the javascript console these little errors.

Looping over attributes in validation fails to stop set of attribute

Normally in my backbone validation, I have a crazy amount of if() statements, as I've seen in many other code samples as well. Validation is pretty much a crap shoot in backbone; however, the if() way seems to work. I want to clean up the code a bit and wrote some code that does return error which should stop backbone from saving the attribute, but it doesn't!
OLD Code that works
validate : function(attr){
if(attr.firstName){
var defaultValue = 'first name',
value = attr.firstName.toLowerCase();
if(value == defaultValue){
return 'error';
}
}
}
NEW code that doesn't work
//My default strings from another place
MyApp.strings.defaults = {
firstName : 'first name'
}
//Model Validate function
validate : function(attr){
jQuery.each(attr, function(key, value){
var defaultValue = MyApp.strings.defaults[key];
if(defaultValue){
defaultValue = jQuery.trim(defaultValue.toLowerCase());
if(value == defaultValue){
console.log(value, defaultValue); //fires, and outputs both as being the same
return 'error';
}
}
});
}
Are you not allowed to loop over the attributes in Backbone validation?
You are not returning any value from the validate method, you were returning 'error' from the each() callback method, not from validate
//My default strings from another place
MyApp.strings.defaults = {
firstName : 'first name'
}
//Model Validate function
validate : function(attr){
var error;
jQuery.each(attr, function(key, value){
var defaultValue = MyApp.strings.defaults[key];
if(defaultValue){
defaultValue = jQuery.trim(defaultValue.toLowerCase());
if(value.toLowerCase() == defaultValue){
console.log(value, defaultValue); //fires, and outputs both as being the same
error = 'error';
return false;
}
}
});
return error;
}

Categories