Ok with the help of stackers I was able to get an error message to show up below input form.
What I need is the error message to not be displayed when the user enters in any input in the form. What am I doing wrong?
Heres the HTML
<form id="url">
<input type="text" name="urlName">
<input type="submit" value="Build Your App"></input>
</form>
<div id="error-message">
</div>
Heres the JS
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let errorMessage = document.getElementById("error-message").innerHTML = "Please provide your store URL";
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName") === "")
return errorMessage;
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
You are assigning the error message to the error message container div regardless of if there's an error which is causing the message to appear in ANY case.
Refer below snippet where I've moved the error message assignment inside the error condition.
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let errorMessage = "Please provide your store URL";
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName") === "") {
document.getElementById("error-message").innerHTML = errorMessage;
}
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
<form id="url">
<input type="text" name="urlName">
<input type="submit" value="Build Your App"></input>
</form>
<div id="error-message">
</div>
Related
I am trying to validate the email input box to return an error when it is empty or when it does not match the email regex pattern. If email input is empty I should get an error and if email input is not empty but does not meet the pattern I should get a new error. So far I am only getting one error
const form = document.querySelector("form"),
user = document.getElementById("name"),
email = document.getElementById("email"),
emailField = document.getElementById("email-field"),
msg = document.getElementById("comment"),
errorMsg = document.getElementsByClassName("error"),
container1 = document.getElementById("form-container"),
container2 = document.getElementById("form-container2");
let field = (id, serial, message) => {
if (id.value.trim() === "") {
errorMsg[serial].innerHTML = message;
id.classList.add("invalid");
} else {
errorMsg[serial].innerHTML = "";
id.classList.remove("invalid");
}
}
// Email Validtion
function checkEmail() {
const emaiPattern = /^[^ ]+#[^ ]+\.[a-z]{2,3}$/;
if (!email.value.match(emaiPattern)) {
console.log("no match");
errorMsg[1].innerHTML = "message";
// email.classList.add("invalid"); //adding invalid class if email value do not mathced with email pattern
} else {
console.log("matches");
// emailField.classList.remove("invalid"); //removing invalid class if email value matched with emaiPattern
}
}
form.addEventListener("submit", (e) => {
e.preventDefault();
field(user, 0, "Name cannot be blank");
field(email, 1, "Email cannot be blank");
field(msg, 2, "Message cannot be blank");
checkEmail();
if (!user.classList.contains("invalid") &&
!email.classList.contains("invalid") &&
!msg.classList.contains("invalid")
) {
location.href = form.getAttribute("action");
container1.classList.add("hide");
container2.classList.remove("hide");
}
});
<div class="form-field">
<input type="text" id="email" placeholder="Email Address">
<div class="error"></div>
</div>
I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
I have a problem. I need to do that if a user writes a correct password, he will be redirected to another page. What's wrong with this? :/
Thanks for answers!
<section>
<input type="password" id="heslo" name="heslo">
<button id="ok">OK</button>
<script>
var pass = document.getElementById("heslo");
var pass1 = "CorrectPassword";
var ok = document.getElementById("ok");
if (ok.onClick) {
if (pass === pass1) {
document.Write('');
}
}
</script>
</section>
You need to add function to your button and compare value of pass using pass.value. Because when you use pass you get refer to html-element and trying to compare it with the string. And for redirect you can use window.location.href =
Tryout this:
<section>
<input type="password" id="heslo" name="heslo">
<button id="ok">OK</button>
<script>
var pass1 = "CorrectPassword";
var ok = document.getElementById("ok");
ok.addEventListener('click', ()=> {
var pass = document.getElementById("heslo");
if(pass.value === pass1) {
window.location.href = 'Rozvrh.html';
}
else alert('Passwords do not match');
})
</script>
</section>
You need to get the value of the input right now you have just targeted that input
var pass = document.getElementById("heslo");
you need to get the value of this input try this
var pass = document.getElementById("heslo").value;
You need use window.location.href = url to redirect to your URL.
Also your code can not run because typo onClick and wrong event handler, and did not get value for pass element.
I update your code to runable as
var ok = document.getElementById("ok");
ok.onclick = function() {
var pass = document.getElementById("heslo");
var pass1 = "CorrectPassword";
if (pass.value === pass1) {
window.location.href = "Rozvrh.html";
} else {
alert('wrong pass');
}
}
var ok = document.getElementById("ok");
ok.onclick = function() {
var pass = document.getElementById("heslo");
var pass1 = "CorrectPassword";
if (pass.value === pass1) {
window.location.href = "Rozvrh.html";
} else {
alert('wrong pass');
}
}
<input type="password" id="heslo" name="heslo">
<button id="ok">OK</button>
When i click a field and pass another, span tag is getting red color. Then i press the submit button it is showing alert message. But when i turn to red span and fill in the field and press submit button it is showing success even if other fields are blank.
const regForm = document.getElementById('regForm');
var validObjects = document.querySelectorAll('[customValidate]');
validObjects.forEach(function(element) {
element.addEventListener('blur', function() {
var emoji = element.previousElementSibling;
var label = emoji.previousElementSibling;
if (!element.value) {
emoji.className = "far fa-frown float-right text-danger";
var span = document.createElement("span");
span.innerHTML = " * Required";
span.style.color = "red";
if (!label.getElementsByTagName("span")[0])
label.appendChild(span);
isValid = false;
} else {
emoji.className = "far fa-smile float-right text-success";
var span = label.getElementsByTagName("span")[0];
if (span)
label.removeChild(span);
isValid = true;
}
});
});
regForm.addEventListener('submit', function(event) {
event.preventDefault();
var isValid = true;
validObjects.forEach(function(element) {
isValid = element.value ? true : false;
})
if (!isValid) {
alert("empty!");
} else {
alert("success!");
}
});
JSFiddle :https://jsfiddle.net/roop06/cjmdabrf/
because isValid is only going to be equal to the last item in the forEach
validObjects.forEach(function(element) {
isValid = element.value ? true : false; // replaces false with true on last iteration
})
If you want to use a forEach you would want to code it like this so it does not overwrite isValid. It uses its previous state.
var isValid = true;
validObjects.forEach(function(element) {
isValid = element.value ? isValid : false;
})
But if you are not doing anything else in the forEach loop, there is a better option. That option is to use every which will exit when it gets to false.
var isValid = validObjects.every(function (element) {
return element.value.length
})
var form = document.querySelector('form');
var validObjects = Array.from(document.querySelectorAll('[customValidate]'));
form.addEventListener("submit", function (e) {
var isValid = validObjects.every(function (element) {
return element.value.length
})
return isValid
})
<form>
<input customValidate>
<input customValidate>
<input customValidate>
<button>submit</button>
</form>
Or you can just use the built in HTML5 validation using required and let the browser do it for you.
<form>
<input customValidate required>
<input customValidate required>
<input customValidate required>
<button>submit</button>
</form>
Try this
JSFiddle
validObjects.forEach(function(element) {
if(!(element.value)){
isValid = false;
}
})
The problem you have is that if the last field is valid then the isValid flag will always be true. One way to get around this is to stop setting the flag once you have determined that there is an invalid field:
validObjects.forEach(function (element) {
if (isValid) {
isValid = element.value ? true : false;
}
});
I have a form, a simple form:
<form>
<input class="u-full-width" type="text" placeholder="First Name" id="firstNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="text" placeholder="Last Name" id="lastNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="email" placeholder="Email" id="emailInput">
<span class="error" aria-live="polite"></span>
<select class="u-full-width" name="state" id="stateInput">
<option value="selectstate">State</option>
</select>
<span class="error" aria-live="polite"></span>
<input id="submit" class="button-primary submit_button" type="submit" value="Submit">
<span class="success" aria-live="polite"></span>
</form>
Essentially I have a eventHandler wired to the form which is listening for the submit event.
theForm.addEventListener('submit', function(e) {
var x = validate(e);
if (x) {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
console.log('There is now data from the form: :) ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
}
}, false);
The validate function:
function validate(e) {
var formData = {
'firstName': null,
'lastName': null,
'email': null,
'stateInput': null
}
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if ((firstNameInput.value == '') || (firstNameInput.value == null)) {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if ((lastNameInput.value == '') || (lastNameInput.value == null)) {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if ((stateInput.value == 'selectstate')) {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
console.log('There is no data from the form: ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return false;
} else {
return true;
}
}
I would think the conditional in the handler would work like this:
It would only fire if the x was true; which it would be if there was a true outcome i.e. the form submitted successfully. the obj, would get filled with the dat and then I would console.log the fields via a for in loop
I am having problems understanding why you can't get data from this function?
Any help would be appreciated...
var formData = { is contained within your validate() function but you are trying to access it from within the anonymous form submit function.
To access it in both places, you either need to pass it as an argument or declare it in a higher scope, outside of both functions like this:
var formData = {
firstName: null,
lastName: null,
email: null,
stateInput: null
}
function validate(e){
}
theForm.addEventListener('submit', function(e) {
});
Additionally, right now, your "State" dropdown will always fail validation because you only have one choice and that choice is considered invalid by your validation function.
Your tests for input in the text fields that check for null is not going to help you at all because an input that contains no data will always return '', which you are already testing for, so just that one test is fine, although you may want to change it to test for: input.value.trim() === '' because the trim() function will remove any leading or trailing spaces in the input.
Finally, when all the form data is valid, you will only see the console report for a brief moment, because the form will submit and cause a redirect to the form's action, so the current page will unload and the console will clear itself out.
Here's the whole thing put together:
var formData = {
firstName: null,
lastName: null,
email: null,
stateInput: null
}
var theForm = document.querySelector("form");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
var emailInput = document.getElementById("emailInput");
var stateInput = document.getElementById("stateInput");
theForm.addEventListener('submit', function(e) {
if (validate(e)) {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
logger('There is now data from the form: :) ');
}
}, false);
function validate(e) {
// Error tracking variable
var error = false;
// Do validations
var emailPattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (firstNameInput.value.trim() === '') {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (lastNameInput.value.trim() === '') {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value.trim())) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if (stateInput.value === 'selectstate') {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
logger('There is at least one empty field in the form: ');
return false;
} else {
return true;
}
}
function logger(message){
console.clear();
console.log(message);
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
// This line will fail here in Stack Overflow, but is correct and
// will work in a real browser environment. Uncomment it for your use.
// localStorage.setItem(prop, formData[prop]);
}
}
#spacer { height:100px; }
<form>
<input class="u-full-width" type="text" placeholder="First Name" id="firstNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="text" placeholder="Last Name" id="lastNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="email" placeholder="Email" id="emailInput">
<span class="error" aria-live="polite"></span>
<select class="u-full-width" name="state" id="stateInput">
<option value="selectstate">State</option>
<option value="someSate">Some State</option>
</select>
<span class="error" aria-live="polite"></span>
<input id="submit" class="button-primary submit_button" type="submit" value="Submit">
<span class="success" aria-live="polite"></span>
</form>
<div id='spacer'></div>