Same regex wont work on different input fields? - javascript

I am having a problem with regex and some if statements . I have classic form with "name" , "lastName" and "email".
I am using simple validation with these if statements
function addTask(e) {
const filter = /^([a-zA-Z0-9_\-\.]+)#([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;
const filterName = /[a-zA-Z]/
if (!filter.test(email2.value)) {
alert('please enter valid mail')
}
if (!filterName.test(lastName.value)) {
showError('Please check your last name');
}
if (!filterName.test(yourName.value)) {
showError('Please check your name');
} else {
save(yourName.value, lastName.value, email2.value, text.value);
const div = document.createElement('div');
div.className = "testimonial";
const div2 = document.createElement('div');
div2.className = "pic";
div.appendChild(div2);
const img = document.createElement('img');
img.src = "tormund.png";
div2.appendChild(img);
const p = document.createElement('p');
p.className = "description";
p.appendChild(document.createTextNode(text.value));
div.appendChild(p);
const h3 = document.createElement('h3');
h3.className = "title";
h3.appendChild(document.createTextNode(yourName.value));
div.appendChild(h3);
cards.appendChild(div);
}
e.preventDefault();
}
<input id="name" type="text" name="field1" placeholder="Name*" >
<input id="lastName" type="text" name="field2" placeholder="Last name*">
<input id="emailRev" type="email" name="field3" placeholder="Email *">
name and email if statements works perfectly ,they wont go straight to "else statement" and they stop running the function right away, but when it comes to last name, code continues directly to "else" and execute my card creation.
Also to mention, regex should be only text for both input fields. Does anyone knows where i get this wrong?

Related

Why does my Input doesn't fill the value attribute when It is written

I have an email input and I'm trying to read the input value but It doen't return a value when It is filled.
<input id="email" name="email" required="" type="email" value=" " class="form-control" />
This is the function I'm trying to execute, saving the Value on a variable to use it later.
var email = document.getElementById("email").value;
I have already tried
var email = document.getElementById("email"); console.log(email.value);
But have no luck
In this snippet, you can see how you can get the value of the input field as it changes. My suspicion is that you are trying to get the input's value before the user has filled it in (it's a common mistake)
//var ch = 0;
var in1 = document.querySelector("input");
var in2 = document.querySelector("input:last-of-type");
in1.addEventListener("change", function(e) {
// ch++;
console.log("changed: " + in1.value);
});
in2.addEventListener("keyup", function(e) {
console.log("changed: " + in2.value);
});
<input type="email" />
<input type="email" />

Attach a function after clicking outside the input with javascript and html

My html is:
<input class="UserInfo" type="text" placeholder="phone Format" id="Phone_num">
Here is my js:
function checkPhoneFormat(){
const phone = document.getElementById("Phone_num").value;
const phoneFormatRex = /^\+?[0-9(),.-]+$/;
var match = phoneFormatRex.exec(phone);
if (match) {
document.getElementById("Phone_num").value = phone;
}
else {
document.getElementById("Phone_num").value = "";
}
}
what i want is to check the format of the phone after the user click outside the input field?
document.getElementById("Phone_num").value
AND
document.getElementById("phone_num").value
There is a typo, Attribute values are always case-sensitive.
The id value should either be Phone_num or phone_num
Is this what you are looking for?
var input = document.getElementById("Phone_num");
input.addEventListener("blur", function(){
const phone = document.getElementById("Phone_num").value;
const phoneFormatRex = /^\+?[0-9(),.-]+$/;
var match = phoneFormatRex.exec(phone);
if (match) {
document.getElementById("Phone_num").value = phone;
}
else {
document.getElementById("Phone_num").value = "";
}
})
<input class="UserInfo" type="text" placeholder="phone Format" id="Phone_num">
I believe what you are looking for is
<input type="text" onfocusout="myFunction()">
You can read more about it here W3 Schools onFocusOut

js - multiple if statements, if condition isnt met the following if statements are not checked

I have the following if statements, but if the first condition is not met the following if statements are not checked. I need them all to be checked.
document.addEventListener('DOMContentLoaded', function() {
if(document.getElementById('firstname').value = "unsolicited"){document.getElementById('firstname').value = "";}
if(document.getElementById('mobile').value = "unsolicited"){document.getElementById('mobile').value = "";}
if(document.getElementById('email').value = "unsolicited#gmail.com"){document.getElementById('email').value = "";}
}, false);
Thanks so much in advance!
Actually you assign a value which you like to check.
You could store the wanted id for checking in an array along with the unwanted value and iterate the array and replace the value with an empty string.
document.addEventListener('DOMContentLoaded', function() {
[['firstname', 'unsolicited'], ['mobile', 'unsolicited'], ['email', 'unsolicited#gmail.com']]
.forEach(([id, value]) => {
const element = document.getElementById(id);
if (!element) return;
if (element.value === value) element.value = '';
});
}, false);
<input placeholder="first name" id="firstname" name="form[firstname]" type="text" value="unsolicited">
<input placeholder="mobile" id="mobile" name="form[mobile]" type="text" value="unsolicited">
<input placeholder="email" id="email" name="form[email]" type="text" value="unsolicited#gmail.com">

How do I select the inputted text of a text field?

I'm adding interactivity to a form.
Here is a snippet of the HTML:
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
There is a button at the bottom of the form, 'Register'. If the button is pressed and the Name field is empty, I want to add an alert message, reminding the user to enter their name. I want to do this by amending the label.
I am having trouble trying to select the inputted text of the text-field. Seeing as it's not value or innerHTML? How do I select it?
This is the code I have so far:
// Form validation. Display error messages and don't let the user submit the form if any of these validation errors exist:
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
Use .value to get the value of input field and put css value red in inverted comma as nameLabel.style.color = "red"; Also since you have a
<button type ="submit">submit</button>
you need to stop you page from refreshing. Use e.preventDefault(); for this in your event handler
The flash of error that you get while in console is that red is not defined which it isn't since its a string and you need to give it in "".
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
if(nameInput.value === "") {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>
document.querySelector("button").addEventListener("click", function() {
// Name field can't be empty
var nameInput = document.getElementById("name");
var nameLabel = document.getElementById("nameLabel");
console.log("\"" + nameInput.value + "\"");
if(nameInput.value.length == 0) {
nameLabel.innerHTML = "Name: (please provide name)";
nameLabel.style.color = "red";
}
});
<label for="name" id="nameLabel">Name:</label>
<input type="text" id="name" name="user_name">
<button>Submit</button>

Validate Form - Multiple Error Messages Appearing

I am trying to write a pure JavaScript form validation that will add an error message next to the label elements if the input is empty.
The confirmEmail input gets an additional error message if it does not match the email input
My problem is that if you hit the submit button when all fields are empty, then put a value into the email input but leave confirmEmail empty and hit submit again, both error messages will appear next to the confirmEmail's label. The ideal result would be that confirmEmail only has text that says "Email does not match"
Here is a fiddle: http://jsfiddle.net/R5e2T/
Here is my HTML:
<div id="theForm">
<div>
<label for="firstName">First Name:</label>
<br>
<input type="text" id="firstName" name="first" value="" />
</div>
<div>
<label for="lastName">Last Name:</label>
<br>
<input type="text" id="lastName" name="last" value="" />
</div>
<div>
<label for="email">Email:</label>
<br>
<input type="email" id="email" name="email" value="" />
</div>
<div>
<label for="confirmEmail">Confirm Email:</label>
<br>
<input type="text" id="confirmEmail" name="confirmEmail" value="" />
</div>
<button type="button" id="submitButton">Submit</button>
</div>
Here is my JavaScript:
function validate () {
var theForm = document.getElementById('theForm'),
firstName = document.getElementById('firstName'),
lastName = document.getElementById('lastName'),
email = document.getElementById('email'),
confirmEmail = document.getElementById('confirmEmail'),
label = theForm.getElementsByTagName('label'),
input = theForm.getElementsByTagName('input'),
inputLength = input.length;
// Remove any spans that may have been added by the next for loop
for (var x = 0; x < inputLength; x++) {
var currLbl = label[x];
if ( currLbl.parentNode.getElementsByTagName('span').length > 0 ) {
var span = currLbl.parentNode.getElementsByTagName('span')[0];
removeElement(span);
}
}
// Error checking for the form.
// Add error message next to any element that has a blank value.
for (var i = 0; i < inputLength; i++) {
// innerText for IE, textContent for other browsers
var labelText = label[i].innerText || label[i].textContent;
var currLabel = label[i];
var text = document.createTextNode( labelText + ' cannot be empty');
if ( input[i].value === '' ) {
currLabel.parentNode.style.color = 'red';
currLabel.insertAdjacentHTML('afterend', ' <span>cannot be empty</span>');
}
else if ( input[i].value !== '') {
currLabel.parentNode.style.color = '';
}
}
// Test to see if confirmEmail is equal to email.
// If not add a warning message next to confirmEmail's label
if (confirmEmail.value !== email.value) {
var labelElement = confirmEmail.parentNode.getElementsByTagName('label')[0]
labelElement.insertAdjacentHTML('afterend', ' <span>Email does not match</span>');
labelElement.parentNode.style.color = 'red';
}
// Test to make sure all inputs have a value,
// and that confirmEmail equals email.
if (firstName.value !== '' && lastName.value !== '' && email.value !== '' && confirmEmail.value !== '' && email.value === confirmEmail.value) {
alert("Submitted!!!");
return true;
} else {
return false;
}
};
// Remove Element function
function removeElement(node) {
node.parentNode.removeChild(node);
}
(function () {
var button = document.getElementById('submitButton');
button.addEventListener('click', validate, false);
}());
I forked your fiddle.
What I did was to use innerHtml and just replace the text of the label, instead of creating new span-nodes and appending them to the document.
I store the original label, like "E-Mail" in a dataset variable, so that I can reset the label later.
Another solution is to add this before you add the "Email doensn't match" message:
var oldSpan = labelElement.parentNode.getElementsByTagName('span')[0];
removeElement(oldSpan);
An even better solution would be to check for confirmEmail matching email before checking for empty fields and do not add the "cannot be empty" message if another error message has been added already.

Categories