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!
}
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);
}
}
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;
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")
}
}
In UI, I create a object and set one of the property as boolean :
function UserObject(componentId, componentName, checkedOut) {
this.componentId = componentId;
this.componentName = componentName;
this.checkedOut = checkedOut; //this is boolean variable
}
But from backend, while I set boolean values in my object, json converts it into string.
private UserObject createUserObject(EntityDTO entity) {
UserObject userObject = new UserObject();
userObject.setComponentId(entity.getEntityId());
userObject.setComponentName(entity.getEntityName());
userObject.setCheckedOut(entity.getCheckedOut());
return userObject;
}
Now, here is the problem, I match some conditions twice (1) while creating (2) later while getting data from backend. Whenever I match the conditions for "checkedOut" object, it fails for the case when object comes from backend:
if(cell.value.checkedOut === true){
//some code
}else{
//some more code
}
What should I do? Thanks in advance :)
if(cell.value.checkedOut === "true"){
//some code
}else{
//some more code
}
As it is a string in json now use double quotes for comparision
if you want to convert string "true or false" to boolean type, use eval():
if(eval(cell.value.checkedOut) === true) {
//some code
} else {
//some more code
}
I am making my own MVC framework and I was thinking of a way to do "automatic" client side validation controller.
Among other functionalities, my forms, elements and validators are objects that work together somewhat like this (inside the form object):
$this->addElement('text', 'myInput');
$this->elements['myInput']->addValidators(array
'length' => array('min' => 5, 'max' => 10),
'number' => array('decimals' => 0)
));
In the example above, I created a text input named 'myInput' whose value, according to the validators I added:
Must be >= than 5 characters
Must be <= than 10 characters
Must be a number
Must have no decimals (int only)
When I get the form submission and call a validation function, all works well on the server side. However, what bothered me was having to redo validation on the client side manually. I dislike having to duplicate the same functionality so I came up with a way to create my client side validation from the PHP form object that is already there.
It boils down to having JS validator functions that have the same functionality as the PHP validators and calling a getClientValidatiors() function on elements to create the appropriate <script> in the body which attaches the JS events.
NOTE: Please ignore JS errors, I wrote this as a concept and didn't test anything just yet.
The JS validator functions would work like this:
function lengthValidator(options, value, id){
//Validate according to the options. Return true if valid or false otherwise as well as calling printError function with the message and the id
}
function numberValidator(options, value, id){
//Validate according to the options. Return true if valid or false otherwise as well as calling printError function with the message and the id
}
function printError(error, id){
//Might add more functionality later
document.getElementById(id).innerHTML = error;
}
For example, this is what it would look like in the view:
<?php echo $this->form->elements['myInput]; //The HTML ?>
<?php echo $this->form->elements['myInput]->getClientValidators(); //The JS ?>
Prior to form submission, the result would look like:
<input type="text" name="myInput" id="myInput"/>
<span class="error" id="myInput-error"></span>
<script>
document.getElementById('myInput').addEventListener('blur', function(e){
var value = e.value;
var id = e.id + '-error';
if(lengthValidator({min:5, max:10}, value, id) != true){
return;
}
if(numberValidator({decimals:0}, value, id) != true){
return;
}
});
</script>
I'm looking for a thumbs up or suggestions on how this could work with another technique. If you have any thoughts, I'd like to hear them!
Consider writing the validation specification in such a way that you can automatically validate in JavaScript and PHP.
$input_schema = array(
"foo" => array(
"type" => "number",
"decimals" => 0,
"length" => array(
"min" => 5,
"max' => 10
)
)
);
Then in JS you can do:
var input_schema = <?php echo json_encode($input_schema);?>;
function validate_input(form_values) {
for (var key in input_schema) {
validate_property(input_schema[key], form_values[key]);
}
}
function validate_property(schema_property, value) {
if (schema_property.type === "number") {
validate_number(schema_property, value); // etc
}
}
And you can make a similar implementation in PHP.