JavaScript validation for empty input field
<script type="text/javascript"> function validateForm() { var a = document.forms["Form"]["answer_a"].value; var b = document.forms["Form"]["answer_b"].value; var c = document.forms["Form"]["answer_c"].value; var d = document.forms["Form"]["answer_d"].value; if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") { alert("Please Fill All Required Field"); return false; } }</script>
<form method="post" name="Form" onsubmit="return validateForm()" action=""> <textarea cols="30" rows="2" name="answer_a" id="a"></textarea> <textarea cols="30" rows="2" name="answer_b" id="b"></textarea> <textarea cols="30" rows="2" name="answer_c" id="c"></textarea> <textarea cols="30" rows="2" name="answer_d" id="d"></textarea></form>
Simple Form Validation to Check Empty Inputs and Display Message
The code you have overwrites the innerHTML completely every time it finds an empty field. What you should do instead is keep an array of all the empty fields, then only write the innerHTML once after the loop, with the list of fields it found.
let inputFields = document.getElementsByClassName('formInput');
const emptyFieldNames = [];
for (var i = 0; i < inputFields.length; i++) {
if (inputFields[i].value === '') {
emptyFieldNames.push(inputFields[i].getAttribute('name'));
}
}
if (emptyFieldNames.length > 0) {
document.querySelector('#fail-message').innerHTML = 'Please fill out the following fields: ' + emptyFieldNames.join(', ');
}
Form Validation: messages not displaying when all input fields are left empty
You have too much javascript code, you can simplify that, alot.
to check if any of the inputs are empty, you can first store all the inputs in a variable like that:
let inputs = document.querySelectorAll('.form input') //This will make a Nodelist array of all the inputs inside the form.
let labels = document.querySelectorAll('.form label') //This will make a Nodelist array of the label tags inside the form
after that you can loop through the inputs array to find if any of the inputs are empty:
for (let i = 0; i < inputs.length; i++) {
if (inputs.value.length == 0) {
inputs[i].style.borderColor = 'red'
label[i].textContent = 'Please fill in this input'
}
}
Check input field is empty or not
You need to get the value after clicking the button. If you put it outside of the click event, the value will never be updated.
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function () {
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if (checkUserName.length == 0) {
console.log('enter name')
} else {
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername" />
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname" />
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber" />
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
Javascript: Empty input with attribute required
This code should work.
Several weird things I think you should change.
- You doesn't have the
eventListener
, so once the document load, it will check if the input has value or not (which always be""
) - You have several things in the
input
hasrequired
attribute, so you have to usequerySelectorAll
instead ofquerySelector
and a loop to loop it
document.querySelectorAll('[required]').forEach(item=>{
item.addEventListener('change',check)
window.addEventListener('load',check)
})
function check(){
for(let i of document.querySelectorAll('[required]')){
if (!i.value) {
document.querySelector('.button').disabled = true;
break;
} else {
document.querySelector('.button').disabled = false;
}
}
}
.button {
color: #fff;
background-color: #007bff;
border: none;
display: inline-block;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
cursor: pointer;
}
.button:disabled {
color: #a2a5a9;
border-color: #c9ced3;
background-color: #f2f2f2;
cursor: text;
}
<form class="form" id="form">
<input type="number" id="a" class="a" placeholder="000" required>
<input type="number" id="b" class="b" placeholder="0">
<input type="number" id="c" class="c" placeholder="000" required>
<input type="number" id="d" class="d" placeholder="000" required>
<input type="number" id="e" class="e" placeholder="0">
</form>
<button type="submit" value="Ok" id="send" class="button">Ok</button>
Validate empty string in form
In myFunction
you can simple add this code after creating a new instance of FormData
:
if (formData.get("urlName") === "")
return alert('asdsa')
It will stop the whole function because of return
and will alert you that you haven't put anything in the input box.
Actually, the whole code is kinda wrong
Here's the correct version of javascript code:
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName").length === 0)
return alert('Provide valid url')
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 call the myFunction
twice and you don't even prevenDefault from sending form, so the form is sent whatever you do in the myFunction
.
And in HTML you don't need button. You can add input:submit
which will trigger function onclick automatically. Here's the correct html code:
<form id="url">
<input type="text" name="urlName">
<input type="submit">
</form>
Javascript cannot submit form with empty field validation
Looking at your code I found a number of problems:
Invalid telephone number regexp: you are using the following regexp to validate the telephone number field, but it has a missing character:
^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$
// missing ] after 0-9 ^^(I am going to ignore the fact that the regular expression has placeholder 'Mobile number' yet only accepts landline phone numbers for inner and outer London in the UK.)
You are showing validation error messages if the email, password, confirm-password and telephone number fields contain a single space:
if (userObject.email === " " ) {
You probably want to be comparing the values against an empty string instead:
if (userObject.email === "" ) {
The end of your
storeUser()
function is as follows:if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";When do we reach the last two lines, the one that writes to local storage and the one that shows the success message?
- If the telephone number field contains a single space, then a warning message appears and the function returns
false
. - If the telephone number field contains anything other than a single space, the function returns
true
.
The last two lines are unreachable. They are never executed because the function returns before it gets to them.
What you probably want to do is to get rid of the
else
clause and addreturn true;
at the bottom, i.e.:if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
return true;- If the telephone number field contains a single space, then a warning message appears and the function returns
Inconsistent use of
return false;
. If the passwords don't match, or the telephone number field isn't filled out, the function returnsfalse
. There is no correspondingreturn false;
line for the username, email, password and confirm-password fields. Add this line for each of these fields.You aren't clearing the warning message if the form is successfully completed. Add the line
document.getElementById("Warning").innerHTML = "";
to the end of your function.
Incidentally you have various pairs of lines
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";but the first line in each pair is unnecessary because the empty-string value you assign to the inner HTML of the warning element is immediately replaced by the warning message assigned in the second line. You can delete the first line of each such pair.
Related Topics
How to Conditionally Add Attributes to React Components
React Hooks - Right Way to Clear Timeouts and Intervals
Use Dynamic (Variable) String as Regex Pattern in JavaScript
Completely Removing Duplicate Items from an Array
How to Stop Event Bubbling on Checkbox Click
Localstorage Access from Local File
React: How to Load and Render External HTML File
How to Mute an HTML5 Video Player Using Jquery
JavaScript Code Not Work in Head Tag
How to Enable Bootstrap Tooltip on Disabled Button
Differencebetween Window, Screen, and Document in JavaScript
How to Limit Panning in Google Maps API V3
Detect When an Image Fails to Load in JavaScript
Unexpected JavaScript Date Behavior
How to Solve 'Redirect Has Been Blocked by Cors Policy: No 'Access-Control-Allow-Origin' Header'
Reformat String Containing Date with JavaScript