Good night!
I'm developing a project for study and I really wanted to do the validation of the password field and the validation of the confirmSenha field. The idea is that when the user enters a different password, a message is returned saying that the passwords do not match. Below is the scope of my code.
function validarPasswordConfirm(password, confirmPassword) {
var typedpassword = document.getElementsByName('password').value;
var confirmTypedPassword = document.getElementsByName('passwordConfirm').value;
if(typedpassword !== confirmTypedPassword) {
return { value: false, text: 'Passwords are not the same.' }
} else {
return { value: true, text: '' }
}
}
I'm trying to validate the password field with the confirmpassword field
The function getElementsByName returns an array, so you can't access the value property like that.
I recommend use getElementById instead.
I noticed a few problems with your code.
Firstly, var is not used anymore (see why). You should use an alternative.
Alternatives for var are below.
let - Use this for variables that can be changed.
const - Use this for variables that cannot be changed (constant).
Secondly, getElementsByName() returns a NodeList, which is an iterable (like an array). This means that .value is undefined in a NodeList.
To fix it, change your code to below.
const typedPassword = document.querySelector("#password").value;
const confirmTypedPassword = document.querySelector("#passwordConfirm").value;
Related
I’m checking whether there is a placeholder present in the “all” string within alertDetails object so my question is I need to access email,sms,fax property that appears dynamically based on user’s input (the code is a part of an alert box in which an user can choose to send alert via different delivery methods) so I saved all the possible delivery methods in an array and tried like below;
Const delmethod=[“email”,”sms”,”fax”]
for(let i=0;i<delmethod.length;i++)
{
Console.log(alertDetails &&
alertDetails.alertMessage &&
alertDetails.alertMessage[${lang}] &&
alertDetails.alertMessage[${lang}].all
? alertDetails.alertMessage[${lang}][‘${delmethod(i)}’].includes('placeholder')
: false;
}
P.S:the property “all” is fixed it’s just the email fax will be changing based on user’s input, to sum it up I want to return true if “placeholder” exists in any of the strings(all,email,fax,sms) the method I tried just prints the del method array, I’d appreciate any help thanks!
There are multiple issues with your code. You cannot just use ${lang}. You must surround your string with backticks (`) if you want to use template literals.
To access properties of an object you need a a key i.e. a string which you already have so in this case template literals are not required at all.
When you access an array by index you need to use [] not () so use delmethod[i] instead of delmethod(i). Additionally make sure an property exists on an JavaScript object.
const delmethod = ["email", "sms", "fax"];
const alertDetails = {
alertMessage: {
en: {
all: "emailsfsdfsdfsd",
fax: "placeholder",
sms: "sdkjföskjfsödkj"
},
},
};
const lang = "en";
for (let i = 0; i < delmethod.length; i++) {
if (
alertDetails &&
alertDetails.alertMessage &&
// use backticks ` when trying to use template literals
alertDetails.alertMessage[`${lang}`] &&
// there is actually no need for template literals here
alertDetails.alertMessage[lang].all &&
// you need to make sure "sms" or "fax" or "email" key actually exist on the object
alertDetails.alertMessage[lang][delmethod[i]] &&
alertDetails.alertMessage[lang][delmethod[i]].includes("placeholder")
) {
console.log(
`alertDetails.alertMessage[${lang}][${delmethod[i]}] does have a placeholder`
);
console.log(true);
} else {
console.log(
`alertDetails.alertMessage[${lang}] does NOT have property ${delmethod[i]} or does NOT have a placeholder`
);
console.log(false);
}
}
I have a dynamic form validation event listener, which checks if an input is valid or not.
However, even when the input technically isn't valid, the HTML Object Property validity -> Valid is set to "True".
I cant figure out how I can trigger it to change between "True" or "False" based on if it's valid or not in my javascript function.
function validateEventName(){
const reEventName = /^[a-åA-Å0-9]{2,25}$/;
if(!reEventName.test(inputEventName.value)) {
inputEventName.classList.add("is-invalid");
inputEventName.classList.remove("is-valid");
inputEventName.checkValidity();
} else {
inputEventName.classList.remove("is-invalid")
inputEventName.classList.add("is-valid")
}
}
I need to be able to change the inputEventName.valididty.valid between "True" or "False" based on if it's valid or not with the function in my code above.
use document.getElementById()
function validateEventName(){
const reEventName = /^[a-åA-Å0-9]{2,25}$/;
if(!reEventName.test(document.getElementById("dynamicID").value )) {
inputEventName.classList.add("is-invalid");
inputEventName.classList.remove("is-valid");
inputEventName.checkValidity();
} else {
inputEventName.classList.remove("is-invalid")
inputEventName.classList.add("is-valid")
}
}
I need to do a search on a text field (mongodb). The Search criteria / filter on the collection can be any substring of the sting in the field. I save the filter (input) in a session variable. The filter seems to work the first time after the Sessionvariable is null.
After the first search I get no result when I enter a new (extisting!) value. In case I clear the filter, hit enter and than reenter the filter I get the result.
I assume that my code is suboptimal. Can someone please review and maybe make a suggestion?
Here is what I have:
html:
<input class="medinput" maxlength="80" type="text" name="nameSearchBar" id="nameSearchBar" value="{{searchText}}">
javascript:
Session.setDefault('searchText', null);
Template.questions.helpers({
questions:function(){
if ((Session.get('searchText') === null) || (Session.get('searchText') === '')) {
Session.get('searchText',null);
return Questions.find({archived:{$ne:true}});
} else {
var searchText = Session.get('searchText');
Session.get('searchText',null);
return Questions.find( { $and: [ { archived: { $ne: true } }, {note:{$regex: (".*"+searchText+".*") } } ] } )
}
},
searchText:function(){
return Session.get('searchText');
}
})
Template.questions.events({
"change #nameSearchBar":function(event){;
searchText = event.target.value;
Session.set('searchText', searchText);
}
})
Questions:
why do I need to first "enter" an empty string to get a valid result
is this a good procedure? Doesn't hitting enter works against the reactive
approach? I think after enter the complete page is resent ??
Would it be better to check "keyup" for ASCII 27 and 13?
it seems to me that the regex works, are there any concerns? I like to find any substring of the typed in filter, also when the filter has a whitespace.
this is a full text search do I need to set something up on the mongodb side?
Open Question: are the already prebuild implementiations - I do not need to reinvent the wheel...
Here's my interpretation, or how I would possibly have built this:
Template.questions.helpers({
questions:function(){
var searchText = Session.get('search-text');
if(searchText && searchText != '') {
return Questions.find({$and: [{archived: {$ne: true}}, {note:{$regex: (".*"+searchText+".*")}}]});
} else {
return Questions.find({archived: {$ne: true}});
}
}
});
Template.questions.events({
"keyup #nameSearchBar": _.throttle(function(event){
searchText = event.target.value;
Session.set('searchText', searchText);
}), 500)
});
To me it doesn't seem necessary to set a default, or to call Session.get('search-text', null). Also you'll see how my code is a bit more concise. keyup is probably more effective as an event here too.
N.B. The _.throttle is an underscore.js function which will limit changing the Session variable to only every 500ms rather than constantly. This helps save unnecessary server load.
Two pre-built packages that are popular amongst Meteor developers are worth looking into: Easy Search or Search Source
I copied a generally working example for a search on a single text field.
#Ian: Thanks for the suggestion! I took the toggle part, I found that you can not leave the session variable as is, even it gets over written, it must evaluated before. So it has to be set back with NULL.
Session.setDefault('searchText', null);
Template.questions.helpers({
questions:function(){
if ((Session.get('searchText') === null) || (Session.get('searchText') === '')) {
return Questions.find({archived:{$ne:true}});
} else {
var searchText = Session.get('searchText');
return Questions.find( { $and: [ { archived: { $ne: true } }, {note:{$regex: (".*"+searchText+".*") } } ] } )
}
},
searchText:function(){
return Session.get('searchText');
}
})
Template.questions.events({
'keyup #nameSearchBar': _.throttle(function(event){;
Session.set('searchText',null);
searchText = event.target.value;
Session.set('searchText', searchText);
},500)
})
I am working on an assignment using javascript. I am attempting to use filter_var to test if my form has empty fields but I cannot get it to run.
I'm not confident that my Syntax is right.
function validate_reg_form(form)
{
var form = "";
if (filter_var(form, FILTER_VALIDATE_BOOLEAN))
{
alert("validate_reg_form() not yet implemented");//remove this
}
}
filter_var is a PHP function. It does not exist in JavaScript. The exact equivalent is:
var truthyBooleanStrings = ['1', 'true', 'on', 'yes'];
function validateRegForm(form) {
var form = '';
if (truthyBooleanStrings.indexOf(form) !== -1) {
// …
}
}
Maybe that’s not the right approach for
test if my form has empty fields
, though. If you want to test that something is not an empty string, just use !== '' or the implicit truthiness of non-empty strings, as in
if (form) {
// Not empty!
}
I have a form that has five fields; first name, last name, username, password and passwordConfirmation.
I'd firstly like to say that I don't want the most complicated method, this is for a very simple website that will never go live, it is purely for demonstration purposes and I am not to worry about error catching in the sense of harmful user input.
So far I have this:
function validateRegistrationForm(firstName, lastName, username, password, passwordConfirmation) {
alert("validate form function has been called");
//alert("function has been called");
//---
var firstName = firstName;
//alert(firstName);
var lastName = lastName;
//alert(lastName);
var username = username;
//alert(username);
var password = password;
//alert(password);
var passwordConfirmation = passwordConfirmation;
//alert(passwordConfirmation);
//---
//**The code that I have sectioned off here, I am unsure whether I need it or not, could someone please explain to me why I would do this, and not just reference the parameters in the function directly?**
// Check here if all the fields in the registeration form have been filled.
if ( firstname == null || firstname == "" ) {
//firstname hasn't been filled out
}
if ( lastName == null || lastName == "" ) {
//lastname hasn't been filled out
}
if ( username == null || username == "" ) {
//username hasn't been filled out
}
if ( password == null || password == "" ) {
//password hasn't been filled out
}
if ( passwordConfirmation == null || passwordConfirmation == "" ) {
//passwordconfirmation hasn't been filled out
}
}
I would like to have a way to check if each of the fields have been filled out (which I have here I think) and if not, to produce a notification such as a red border around the input element in question and/or a message with instructions on how to resolve the issue. I know this can be done with css but I am not sure of the most efficient way to do it.
Currently I have created these two functions:
function generateError(messageText, elementIdentifier) {
alert("error generator called");
//var element = document.getElementById(elementID);
//var error = document.createTextNode(message);
//element.innerHTML = message;
alert("Element: " + elementIdentifier + ", Reason: " + messageText);
}
function validatePassword(password, passwordConfirmation) {
alert("password check called");
if (password == passwordConfirmation) {
if (password.length < 8) {
//password too short
//alert("password\'s match but they are too short");
return false;
} else {
//passwords match and the right length
//alert("password\'s match and they are 8 characters or longer");
return true;
}
} else {
//the two do not match
//alert("they don\'t match")
generateError("Passwords don\'t match", "password");
return false;
}
}
The validatePassword() function takes the password and the password confirmation as two parameters, I think this works already, what I want is for the errors generated to be passed to the generateError() function which stores them all in an array and then loops through them one by one displaying to the user what is wrong.
Define complicated. I think that your code is already too complicated. The giveaway is that there is repetition. Whenever you see repetition, ask yourself if there is a way to combine all that repetition into a loop. The result is less code but usually also code that is more friendly to change. If you want to add a phone number, for example, you'd have to add four more lines of code as well as another parameter, which will break your function's backward compatibility unless you add even more code allowing for an undefined phone number. You might say "I'm definitely not adding any more fields, so that isn't an issue." I don't know how many times I have said that myself and I ended up having to eat my words and do surgery on my functions. Besides, its just better engineering.
Also, let's revisit your validateRegistrationForm function. The way you have it now, my guess is that it is triggered by onsubmit, but why not take advantage of JavaScript's snappiness by giving the user instant feedback on each field? I'm going to change it to validateRegistrationElement and it will be called onchange. We are only going to pass in one parameter, the textbox being evaluated. That way we can use "this". So each textbox will look something like:
<input type="text" id="firstname" onchange="validateRegistrationElement(this)" />
Also, next to each, let's put a feedback box next to each textbox and get rid of those annoying alert popups. We can even style our feedback box with CSS classnames "error" and "success" and make them red or green, respectively.
<div id="firstnameFeedback"></div>
...and so forth.
The CSS:
.error {background-color: pink; border: 1px dashed red; color: white}
.success {border: 1px dashed green;}
Instead of loading up our function with the details of each form element, let's separate the instructions into a sort of config variable, an array of objects. Each member of the array will represent one form element, so in your case there would be four members of the array. These would be objects which contain everything the function needs to know to report back an error. My suggestion is to let each object contain the id of the form element, a label, a requirement (an array of regular expressions paired with their own feedback messages would be ideal, but let's keep it simple with string length), and a special condition for the passwords matching.
var myFields =
[
{
"id": "firstname",
"label": "first name",
"minLength": 1 //in other words, the field is required
},
{
"id": "lastname",
"label": "last name",
"minLength": 1
},
{
"id": "password1",
"label": "first password",
"minLength": 6,
"maxLength": 8,
"mustMatch": "password2"
},
{
"id": "password2",
"label": "second password",
"minLength": 6,
"maxLength": 8,
"mustMatch": "password1"
},
]
Is this too complicated? I don't think so. Now we have a bucket of legos that our validator function can reach into. We can add or subtract elements easily. We can even add features for later if we want and it won't break the function (like a password maxlength, which I have left out of the function). I'll show you. Here is the new validator function. Remember that this is called whenever the user changes a value in a field. The function will know which one because we used "this" in our html.
function validateRegistrationElement(field) {
var message = ""; //declare an empty string literal for the message
for (i=0;i<myFields.length; i++){ //loop through each array element until we find the object
if(myFields[i].id == field.id){ //once we've found the config object
if(myFields[i].minLength > field.value.length){ //if the field is shorter than what's allowed
message += myFields[i].label + " must be longer than " + myFields[i].minLength;
}
if (typeof(myFields[i].mustMatch) != 'undefined'){ //if the field must match another...
if(field.value != document.getElementById(myFields[i].mustMatch)){ //...does it match
message += myFields[id].label +" must match "+myFields[id].mustMatch;
}
}
document.getElementById(field.id + "Feedback").innerText = message;
if (message.length > 0) {setClass(field.id, "error")} //if there an error message, highlight red
else{setClass(field.id, "success")}//otherwise, highlight green
}
}
}
Notice that this also takes care of the passwords so you don't need an extra function for them.
This function manages the CSS and is called by the above function.
function setClass(id, className) {
document.getElementById(id).className = "";
document.getElementById(id).className = className;
document.getElementById(id+"Feedback").className = "";
document.getElementById(id+"Feedback").className = className;
}
Try great jQuery Validation plugin.
You will need little more markup (see demos and docs) and just $("#yourForm").validate();.