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;
}
});
Related
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>
I need to implement code which should add eventlistener and on change event check if the form is valid and add the message
let validate = function(element, info, functionValidate) {
let htmlTag = document.querySelector('fieldElem');//?
htmlTag.addEventListener('change',ev=>{
let notif = document.createElement('span');
document.htmlTag.appendChild(notif);//should add span element next to input
if(fieldElem.value == '')
{
notif.style.visibility = "hidden"; //hide span if nothing happens
}
//I need to implement code which should add eventlistener and on change event check if the form is valid and add the message...
Try the following. You could also use form validation (see Form Validation Set Custom Validity for an example)
function validator(val) {
return (val != '');
}
function validateField(element, validator, message) {
var helper = document.createElement("span");
var parent = element.parentElement;
parent.appendChild(helper);
element.addEventListener('change', function() {
var val = element.value;
if (!validator(val)) {
helper.innerText = message;
} else {
helper.innerText = "";
}
});
}
validateField(document.getElementById('test'), validator, 'Wrong input');
<html>
<body>
<form>
<input id="test" type="text" placeholder="Type here"/>
</form>
</body>
</html>
I have a input where the user should write ELIMINA so the modal could be submitted, so far I writed this functionality for validation :
var validation = false;
function validateElimina(e) {
var inputField = e.target.value;
if (inputField === 'ELIMINA') {
validation = true;
}
validation = false;
}
function onValidate() {
if(validation == true) {
return console.log('EXISTS')
}
return console.log('FALSE');
}
this is input field :
{props.eliminaInput ? <Input onChange ={(e) => validateElimina(e) } className="elimina-input" type="text" autoFocus={true} /> : null}
and this is the button for submitting :
<Button
onClick={() => onValidate()}
className="button-modal col-5 py-2 text-uppercase">
{props.buttonText}
</Button>
So for now, if I'm pressing the button doesn't matter what is in input field, it's showing FALSE. Help please.
const [inputValue, setInputValue] = useState()
function validateElimina(e) {
const inputField = e.target.value;
setInputValue(inputField)
}
function onValidate() {
if(inputValue == “ELIMINA”) {
return console.log('EXISTS')
}
else
return console.log('FALSE');
}
You are always setting it to false. Move it before the if.
validation = false;
if (inputField === 'ELIMINA') {
validation = true;
}
or use an else
if (inputField === 'ELIMINA') {
validation = true;
} else {
validation = false;
}
I am trying to validate two fields in my form.
But it is displaying the error message only for one field.
Following is Javascript code:
function req() {
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
return false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
return false;
}
}
HTML code:
<input name="txt_fnm" type="text" id="txt_fnm"/> <label id="i"></label>
<input name="txt_lnm" type="text" id="txt_lnm"/>\<label id="i1"></label>
If you need to get all errors tested, as "Disha" commented, you can not put a return statement in each if blocks.
var noError = true;
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
noError = false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
noError = false;
}
return noError;
That should work as you seems to want to.
Try This Code
JavaScript
`
function validate(){
var isValid = true;
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
isValid = false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
isValid = false;
}
return isValid;
}`
I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}