Make a input text format automatically as a date with "/" - javascript

I am making a "subscribe to my newsletter" form and I am using a clothing website as a reference https://www.emibeachwear.com.br/ (You will find the form on the footer of the website)
On the footer there is this input called "data de aniversário" or "birthdate" if you translate it to English.
Using chrome inspect element I saw that it is a Text input. Even though it is a text it still formats as a date.
How do I do that? Should I use javascript? If so, how?
Here is what I have now:
<div class="newsletter" style="background:transparent; color:white;">
<label class="email"> E-MAIL
<input class="caixa" type="email" name="EMAIL" placeholder="E-MAIL" style="border:0;"required />
</label >
<label class="aniversario"> DATA DE ANIVERSÁRIO
<input class="caixa" type="date" placeholder="DATA DE ANIVERSÁRIO" style="border:0;" max-length="10" required />
</label>
<input class="cadastrar caixa" type="submit" value="CADASTRAR" style="border:0;"/>
</div>

Here's one way:
const input = document.querySelector('input');
input.addEventListener("input", function() {
input.value = input.value.replace(/\D/g, "");
var s = input.value.replaceAll("/", "").match(/.{1,2}/g);
if (s != null) {
var len = s.length;
input.value = s.join("/");
if (len > 3) {
var l = input.value.lastIndexOf('/');
input.value = input.value.substring(0, l) + input.value.substring(l + 1);
}
}
})
<input type="text" maxlength="10">

Related

How can I correctly validate a blank field?

Learning Javascript and trying to work out the best way to validate a text and number fields on a form.
I have the following html form:
> <form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br>
<input class="input input1" type="text" id="setName" name="setName" value=" ">*<br>
<label for="setTheme">Set Theme</label><br>
<input class="input input1" type="text" id="setTheme" name="setTheme" value=" "><br>
<label for="setReferenceNumber">Reference Number</label><br>
<input class="input input1" type="number" id="setReferenceNumber" name="setReferenceNumber" value="0">*<br>
<label for="setPieceCount">Piece Count</label><br>
<input class="input input1" type="number" id="setPieceCount" name="setPieceCount" value="0">*<br>
<br>
<input class="input input2" type="button" value="Save Set" onclick="captureLegoSets.captureSets()">
<input class="input input2" type="reset" value="Reset Values">
</form>
And attached Javascript (forgive the numerous console.log statements):
this.captureSets = function(){
let setName = " ";
let setTheme = " ";
let setReferenceNumber = 0;
let setPieceCount = 0;
let formFields = document.querySelectorAll(".input1");
console.log(formFields);
for (let i=0; i < formFields.length; i++) {
console.log(formFields[i]);
console.log(formFields[i].id);
console.log(formFields[i].value);
if ((+document.getElementById(formFields[i].id).value) > 0 | (+document.getElementById(formFields[i].id).length) !== null) {
console.log(formFields[i].id + " = " + formFields[i].value);
if(formFields[i].id === "setName"){
setName = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = +document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = +document.getElementById(formFields[i].id).value;
}
console.log(formFields);
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
}
The problem I'm experiencing if that the else statement keeps triggering for the text fields if I only check the .value, but if I check the .length, it doesn't trigger at all.
I know I could probably put together a bunch of if statements to check for null, empty and so on, but I'm assuming this would just be poor coding on my part. Is there a better/more concise way of checking for valid inputs?
First you have provided default values to all your text fields, which let the following if check resulting in true, since you have provided default values as " " ( " " is not a null )
if ((document.getElementById(formFields[i].id).value > 0) || (document.getElementById(formFields[i].id).length !== null))
In the above expression you have used !== instead of !=
You used | not || for or operation
Remove + before document ( I don't understand why you have added those. Please explain
Hence,
remove default values / check for right conditions in the conditional statements,
use a p tag to display all the errors in the bottom. I have provided a simple example of concatenating the errors, you can also use an array to collect the errors. In the best case a separate error text right below each text field is awesome.
HTML
<form id="captureLegoSets">
<label for="setName">Lego Set Name</label><br />
<input
class="input input1"
type="text"
id="setName"
name="setName"
/>*<br />
<label for="setTheme">Set Theme</label><br />
<input
class="input input1"
type="text"
id="setTheme"
name="setTheme"
/><br />
<label for="setReferenceNumber">Reference Number</label><br />
<input
class="input input1"
type="number"
id="setReferenceNumber"
name="setReferenceNumber"
/>*<br />
<label for="setPieceCount">Piece Count</label><br />
<input
class="input input1"
type="number"
id="setPieceCount"
name="setPieceCount"
/>*<br />
<br />
<input
class="input input2"
type="button"
value="Save Set"
onclick="captureSets()"
/>
<input class="input input2" type="reset" value="Reset Values" />
</form>
<p id="error-text"></p>
JS
captureSets = function () {
let setName = "";
let setTheme = "";
let setReferenceNumber = 0;
let setPieceCount = 0;
let errorText = "";
let formFields = document.querySelectorAll(".input1");
for (let i = 0; i < formFields.length; i++) {
if (
(document.getElementById(formFields[i].id).value > 0) ||
(document.getElementById(formFields[i].id).length != null)
) {
if (formFields[i].id === "setName") {
setName = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setTheme") {
setTheme = document.getElementById(formFields[i].id).value;
}
if (formFields[i].id === "setReferenceNumber") {
setReferenceNumber = document.getElementById(
formFields[i].id
).value;
}
if (formFields[i].id === "setPieceCount") {
setPieceCount = document.getElementById(formFields[i].id).value;
}
} else {
alert("Please add non-zero values to " + formFields[i].id);
}
}
if (!setName || setName == "") {
errorText += " Fill the name text field <br>";
}
if (!setPieceCount) {
errorText += " Fill the piece count text field <br>";
}
if (!setTheme || setTheme == "") {
errorText += " Fill the theme text field <br>";
}
if (!setReferenceNumber) {
errorText += " Fill the reference number text field <br>";
}
document.getElementById("error-text").innerHTML = errorText;
};
This may or may not help you, but I think, this is easier for you to check this directly by pattern attribute. You just need to put some regex.
An HTML form with an input field that can contain only three letters (no numbers or special characters):
<form>
<label for="country_code">Country code:</label>
<input
type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}"
title="Three letter country code">
</form>
https://www.w3schools.com/tags/att_input_pattern.asp

html javascript form no longer working since adding new input field

I have the following html and javascript code for validation on the input fields, this was working with the one input field for first name but since I tried to extend my code by adding a new input field for last name now the form validation has stopped working as follows:
function myFunction() {
let x = document.getElementsByName("first_name").[0]value;
let y = document.getElementsByName("last_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
if (y == '' || y == null) {
text = "Input not valid";
}
document.getElementById("last_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
document.getElementsByName("last_name").focus();
};
})(), true);
</head>
<body>
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<br><br>
<input type="text" name="last_name" placeholder="last name" name class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="myFunction()">
How can I get this back working with the extra input field last name added? Thanks in advance
there are many errors here. you may find them by your own by debugging your console.log
error, at let x = document.getElementsByName("first_name").[0]value;
there are a to many }
eventlisteners need to be on the input and shouldn't be inside the check function
there are empty name attributes on your inputs
fixing it blind it would be something like:
let firstName = document.getElementsByName('first_name')[0];
let lastName = document.getElementsByName('last_name')[0];
function checkValid() {
let x = firstName.value;
let y = lastName.value;
let text;
text = '';
if (x == '' || x == null) {
text = 'Input not valid';
}
document.getElementById('first_name_errors').innerHTML = text;
if (y == '' || y == null) {
text = 'Input not valid';
}
document.getElementById('last_name_errors').innerHTML = text;
}
firstName.addEventListener('invalid', function () {
firstName.focus();
});
lastName.addEventListener('invalid', function () {
lastName.focus();
});
<input type="text" name="first_name" placeholder="first name" class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="checkValid()">
<br><br>
<input type="text" name="last_name" placeholder="last name" class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="checkValid()">

My form Verification and Validation with JS is not working

I want to verify and validate a form in HTML, and insert messages in Front if necessary ("eg.Pseudo/Username not long enough"), which will serve as a "new user" form for a website.
I want to start by understanding my mistake for the "Pseudo" verification and validation.
I currently have the following in HTML:
<form id="formNouveau" onsubmit="return valideForm2()">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the following in JS (focusing on the pseudo validation):
function valideForm(){
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
function valPseudo(text)
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of text.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert ("Please write a pseudo");
if (letterCount + numberCount > 40)
alert ("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert ("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert ("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert ("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
}
What do you think?
Thank you!
You have a mix of variable names in the function and a sub function with incorrect syntax. You're not preventing the form from submitting. Fixed both and it works:
function valideForm(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of valPseudo.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (valPseudo == "")
alert("Please write a pseudo");
if (letterCount + numberCount > 40)
alert("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
alert("Pseudo is too short") //The name is too short
if (letterCount < 1)
alert("one letter needed at least") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
alert("one number needed at least") //There aren't enough [0-9] characters
return 0 //Everything is okay!
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
<form id="formNouveau">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
function valideForm2(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var msgPseudo = document.getElementById("msgPseudo");
console.log(valPseudo);
function validate(text) {
let letters = "abcdefghijklmnopqrstuvwxyz";
let numbers = "0123456789";
let letterCount = 0;
let numberCount = 0;
for (let character of text.toLowerCase()) {
if (letters.includes(character)) ++letterCount;
else if (numbers.includes(character)) ++numberCount;
else return false; //A non [a-zA-Z0-9] character was present
}
if (text == "") alert("Please write a pseudo");
if (letterCount + numberCount > 40) alert("Pseudo is too long"); //The name is too long
if (letterCount + numberCount < 5) alert("Pseudo is too short"); //The name is too short
if (letterCount < 1) alert("one letter needed at least"); //There aren't enough [a-zA-Z] characters
if (numberCount < 1) alert("one number needed at least"); //There aren't enough [0-9] characters
return 0; //Everything is okay!
}
validate(valPseudo);
}
const form = document.getElementById("formNouveau");
form.addEventListener("submit", valideForm2);
Try this JS code instead, it has the same functionality but has some modifications, the main problem was regarded to e.preventDefault() which forces page not to reload. Moreover you had some little bugs. For more information on preventDefault you can visit link: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You're better off testing the input against a REGEX expression rather than testing for each failure case...
There a numerous REGEX testers and cheat-sheets online for what you're trying to do.

How to display multiple inputs on the same page in a container

I'm trying to display details inputted into the form in the div on the same page, when the submit button is clicked, it doesn't display.
<script type="text/javascript">
function checkinput(){
var a,b,c,d;
a = document.getElementById("fname").value;
b = document.getElementById("lname").value;
c = document.getElementById("address").value;
d = document.getElementById("email").value;
document.getElementById('output').innerHTML = a + b + c + d ;
}
</script>
<form id = "myform" onsubmit ="return false" >
<p>Firstname : <input type="text" name="Firstname" id="fname" value=""></p>
<p>Last name : <input type="text" name="lastname" id="lname" value=""></p>
<p>Address : <input type="text" name="Address" id = "address" value=""></p>
<p>Email : <input type="email" name="Email" id = "email" value=""></p>
<button onclick = "check()">submit</button>
</form>
<div id="output" style="width: 200px; height: 200px;border: 1px solid black">
</div>
I expect details inputted in the form to display in the div element below.
Just rename the method you try to call when button is clicked.
<button onclick="checkinput()">submit</button>
To put every part on its own line, add the "" between them
document.getElementById('output').innerHTML =
a + "<br/>" + b + "<br/>" + c + "<br/>" + d;
UPD
you can set the default type of the button to the "button" as it was recommended above and in this case, you don't need to handle the "onsubmit" event for the form
<form id="myform">
<p>Firstname : <input type="text" name="Firstname" id="fname" value=""></p>
<p>Last name : <input type="text" name="lastname" id="lname" value=""></p>
<p>Address : <input type="text" name="Address" id="address" value=""></p>
<p>Email : <input type="email" name="Email" id="email" value=""></p>
<button type="button" onclick="checkinput()">submit</button>
</form>
After that, you can use different js functions depending on your purposes
// Strait forward - just get names from the array and use the values
// in any way you like
function checkinput1() {
let html = "";
for(let name of ["fname", "lname", "address", "email"]) {
html += document.getElementById(name).value + "<br/>";
}
document.getElementById('output').innerHTML = html;
}
// If you need just to concatenate values
function checkinput2() {
document.getElementById('output').innerHTML = `${document.getElementById('fname').value}
<br/>${document.getElementById('lname').value}
<br/>${document.getElementById('address').value}
<br/>${document.getElementById('email').value}`;
}
// When you want to get all values from the form inputs and don't
// care about their real names. You can also skip the empty values, so
// no empty lines will be added to the result
function checkinput3(){
let values = [];
for(let elem of document.querySelectorAll('#myform input')){
if(elem.value) values.push(elem.value);
}
document.querySelector('#output').innerHTML = values.join('<br/>');
}

Make form validation via custom attributes

please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>

Categories

Resources