Javascript form validation error - javascript

<html>
<head>
<title> Form Validation </title>
<style type="text/css">
fieldset { width: 280px; padding: 6px; }
label { float: left; width: 100px; font: 12px Arial; padding: 5px; }
input { margin-bottom: 5px; }
</style>
</head>
<body>
<form id="inputForm" onsubmit="return validateForm();" action="#">
<fieldset>
<label>First Name:</label><input type="text" name="first_name" /><br />
<label>Surname:</label><input type="text" name="surname" /><br />
<label>Postcode:</label><input type="text" name="postcode" /><br />
<label>Email:</label><input type="text" name="email" /><br />
<input type="submit" name="submit" value="Send form" />
<input type="reset" name="reset" value="Reset" />
</fieldset>
</form>
<script type="text/javascript">
function validateForm() {
var form = document.forms['inputForm'];
var formats = {
First_name: /^[a-z]+[\-`\s]?[a-z]+$/i,
Surname: /^[a-z]+[\-`\S]?[a-z]+$/i,
Postcode: /^\d{4}$/,
Email:/^w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/
};
var elCount = form.elements.length;
for(var i = 0; i <elCount; i++) {
var field = form.elements[i];
if(field.type == 'text') {
if(!formats[field.name].test(field.value)) {
alert('Invalid '+field.name.replace('_', ' '));
field.focus();
return false;
}
}
}
}
</script>
</body>
</html>
Hey guys trying to figure out why the code is giving me a error:underfinded formats[fields.Name] but its has been defined. Its just a simple form so I am not sure what I am doing wrong. Sorry for the basic question but I have been looking over it multiple time and can't see it. Cheers again.

Assuming the error you are talking about is on this line:
if(!formats[field.Name].test(field.value)) {
I'd suggest using a lowercase "n" in the "name" property:
if(!formats[field.name].test(field.value)) {
JavaScript is case sensitive.
UPDATE: In addition to what I've already mentioned, but still regarding case sensitivity, your formats object has property names with mixed case, e.g., First_name, but the corresponding input elements have a name attribute in lowercase, e.g., name="first_name", so when you retrieve an element's name and try to use it to look up the property in formats it will return undefined. You need to make those match case.
Fix those errors and it works: http://jsfiddle.net/M4Nzr/

Related

Change the CSS when there is a required element

I'm a student developer and I'd like to make a message appear when I click on the submit button but there's still a select required
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<p class="messagerequire">Test, If there is a require to submit I appear ! </p>
Here it has the style display:none and I thought I would do that if the form doesn't validate because of a requirement, it changes the CSS.
I've been searching since this morning for answers, but I haven't found or understood.
<input type="submit" name="register" value="register">
Thanks you
Simply check if the select input is invalid in your submit handler, then change the display property for that p element (in this case the first element that has the class). Not the most elegant solution but the simplest in your case:
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', function() {
document.getElementsByClassName('messagerequire')[0].style.display = 'block';
})
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<p class="messagerequire">Test, If there is a require to submit I appear !</p>
<input type="submit" id="submit">
A better approach in my view would be to have two classes for showing and hiding the error and dynamically toggling the p elements' class instead of modifying it's styles.
you code should be something like below. becuase you are using input type=submit so before submit it should validate.
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.getElementById('error').style.display='block';
return false;
}
}
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<form name="myForm" action="/page.php" onsubmit="return validateForm()" method="post">
<p class="messagerequire" id='error'>Test, If there is a require to submit I appear ! </p>
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
You need to use JavaScript to achieve this.
function submitThis(){
let name = document.getElementById("name").value;
if(name.length === 0){
document.getElementsByClassName("error")[0].innerText = "Cannot leve name empty.";
//Removing(hinding) the error after 5 seconds.
setTimeout(()=>{
document.getElementsByClassName("error")[0].innerText = "";
}, 5000);
}
}
.error {
color: red;
}
<input type="text" palceholder="Name" id="name" required />
<br>
<br>
<p class="error"></p>
<br>
<br>
<button onclick="submitThis()">SUBMIT</button>
Please you try it.
$('#submit').click(function(){
$('.messagerequire').css('display','block');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.messagerequire {
color: red;
display: none;
}
</style>
<body>
<p class="messagerequire">Test, If there is a require to submit I appear !</p>
<input type="submit" id="submit">
</body>

How to display entered text in an textbox?

I would like to enter a text in an input field and have it displayed in a text box.
I think it's easy. I need one Input for enter a text, a button and a textbox to show my text. But my code doesn't work.
This is my code:
<!DOCTYPE html>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
function ausgabe(){
var text=document.getElementById("text");
var Wiedergabe=document.getElementById("Wiedergabe");
var Text=text.value;
Wiedergabe.value=Text
}
</script>
<div class="Webview">
<div class="message_container" id="myForm" ></div>
<form class="send_container">
<input type="text">
<button type="submit"
value="Nachricht absenden"
onclick="ausgabe">
</form>
</div>
#charset "UTF-8";
.Webview{
height: 400px;
width: 300px;
}
.message_container{
height: 80%;
width: 100%;
border:5px solid green;
}
.send_container{
height: 20;
width: 100%;
}
.send_container input{
width: 70%;
height:20%
border:2px solid #1CE615;
}
.send_container button{
width: 30%;
height:20%;
}
I think you somehow did some misconceptions about id and naming, you are trying to access elements with wrong names - a solution can be the following:
<input id="textField" type="text">
<p>
<input type="button" id="theButton" value="click me!"
onclick="document.getElementById('div').innerHTML =
document.getElementById('textField').value" />
</p>
<h3><div id="div"></div></h3>
I found few issues in your code, let me summarize that here:
For input element for user provided text you had the <input type="text"> which should have an id attribute as well in order to catch by getElementById.
In order to find an aim element, you need to also provide a proper id or class. I guess with the message_container you can achieve that by using document.getElementsByClassName('message_container')[0]. Then you can set the value of that element with innerHTML property.
So based on my explanation I think this solution can work for you:
const ausgabe = () => {
const textInput = document.getElementById("text");
const messageContainer = document.getElementsByClassName('message_container')[0];
messageContainer.innerHTML = textInput.value;
}
<div class="Webview">
<div class="message_container" id="myForm"></div>
<form class="send_container">
<input id="text" type="text" />
<button type="button" onclick="ausgabe()">Nachricht absenden</button>
</form>
</div>
I hope this helps!

HTML Form onSubmit being bypassed

I'm new to HTML and JS and I'm trying to setup a "Contact" page using GitHub Pages. I am using formspree.io to submit the forms and e-mail to the app mail account.
Here is the deal: I'm trying to setup a simple validation just to verify if the form fields aren't empty (there is no need for a server-side validation), but the "onSubmit" response seems to be bypassed every single time.
Here is my contact.html file:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Helvetica;}
* {box-sizing: border-box;}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical;
}
input[type=submit] {
background-color: #b00faa;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 15px;
}
input[type=submit]:hover {
background-color: #780774;
}
.container {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
</head>
<body>
<h3>Formulário de Contato</h3>
<div class="container">
<form action="https://formspree.io/myEmailHere#mail.com" method="post" onsubmit="return validate();">
<label for="fname">Nome Completo</label>
<input type="text" id="fname" name="fname" placeholder="Seu nome completo...">
<label for="email">E-mail</label>
<input type="text" id="email" name="email" placeholder="Seu e-mail...">
<label for="subject">Mensagem</label>
<textarea id="subject" name="subject" placeholder="Digite algo..." style="height:200px"></textarea>
<input type="submit" value="Enviar">
</form>
</div>
<p id="error_catch"></p>
<script>
function validate() {
var at = document.getElementById("email").value.indexOf("#");
var message = document.getElementById("subject").value;
var fname = document.getElementById("fname").value;
if (fname.length < 1) {
alert("Digite seu nome...");
return false;
}
if (at === -1) {
alert("E-mail inválido!");
return false;
}
if (message.length < 1) {
alert("Digite uma mensagem");
return false;
}
return true;
}
</script>
</body>
</html>
If I open the file locally on Google Chrome, it works just fine, the alerts show up and the form is not submitted until all fields have been filled.
When I open it on my GHPages, however, it bypasses the validate function and proceeds to Formspree captcha page.
A little bit more context (not sure if it influences)...
This file is being included on my index.html file using a JS function.
My index consists of 2 tabs that load a different HTML when clicked.
Here is the GitHub repo for more information: TellMeApp/support.
What I have already tried:
Correcting the Javascript function: I am aware that if an error is raised on the function, the submission follows on without validation.
Creating an additional function to submit the form via JS: works the same locally, not online...
Looking for solutions on Github Pages help: did not found anything related to this subject.
Any thoughts on what could be wrong here?
I thank you in advance!
Instead of using the onsubmit attribute, you can use the required attribute for the inputs like so:
<label for="fname">Nome Completo</label>
<input type="text" id="fname" name="fname" placeholder="Seu nome completo..." required>
<label for="email">E-mail</label>
<input type="text" id="email" name="email" placeholder="Seu e-mail..." required>
<label for="subject">Mensagem</label>
<textarea id="subject" name="subject" placeholder="Digite algo..." style="height:200px" required></textarea>
If you are interested in reading more about the required attribute, you can find it here: HTML required Attribute - W3Schools.com

How to make a input in HTML in JS to integer

So I can not make the input into a integer. I want to turn this into a int so then it can calculate the age of you. I have been researching but can not find the right answer.
HTML CODE:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>learn</title>
<script src="script.js"></script>
</head>
<form action="/learn.html">
<b>Year Born:</b> <input id="input988744" type="value">
</form>
<button onClick="calculateAge(birthYear);">Summit</button>
<body>
</body>
</html>
Javascript Code:
/*
Function
*/
// var
var birthYear;
birthYear = document.getElementById("input988744");
// function
function calculateAge(birthYearInFun) {
"use strict";
console.log(2018 - birthYearInFun); // make it a number
}
2 things needs to be changed
HTML:Change type of <input> from text to number, number can be negative so can add parameter min="1900" to stop from entering date earlier then 1900
<b>Year Born:</b> <input id="input988744" type="number" min="1900">
Javascript: Need to fetch value of HTML element, thus add .value adter getElementById, as getElementById gives HTML element not its value. To be on safer side use parseInt() or Number() over birthYear
var birthYear;
birthYear = Number(document.getElementById("input988744").value);
or
birthYear = parseInt(document.getElementById("input988744").value);
Both these will make birthYear number.
What you really want it looks like is the input type to be a date... Check out the snippet below
legend {
background-color: #000;
color: #fff;
padding: 3px 6px;
}
.output {
font: 1rem 'Fira Sans', sans-serif;
}
input {
margin: .4rem;
}
label {
display: inline-block;
text-align: right;
width: 20%;
}
<fieldset>
<legend>Choose trip dates</legend>
<div>
<label for="start">Start</label>
<input type="date" id="start" name="trip"
value="2018-07-22"
min="2018-01-01" max="2018-12-31" />
</div>
<div>
<label for="end">End</label>
<input type="date" id="end" name="trip"
value="2018-07-29"
min="2018-01-01" max="2018-12-31"/ >
</div>
</fieldset>
You can access the value of the input field as birthYearInFun.value as Mirodinho said and then if it a string, convert it to a number using parseInt().
birthYear = parseInt(document.getElementById("input988744").value)

validating the tag input when it is not filled

I have a tag input it is working but, without entering the value if I click on submit button, it should display an error message like required field
$('#form-tags-4').tagsInput({
'autocomplete': {
source: [
'apple',
'banana',
'orange',
'pizza'
]
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://raw.githubusercontent.com/underovsky/jquery-tagsinput-revisited/master/dist/jquery.tagsinput-revisited.min.css" rel="stylesheet"/>
<script src="https://raw.githubusercontent.com/underovsky/jquery-tagsinput-revisited/master/dist/jquery.tagsinput-revisited.min.js"></script>
<label>Tags input with autocomplete:</label>
<input id="form-tags-4" name="tags-4" type="text" value="">
<button type="submit" id="save" class="btn btn-default ">SAVE</button>
Here is the reference link
Yes, you have this error because Chrome (or other browser) can't focus the element. The original text input is hidden by the plugin.
So you get the error :
An invalid form control with name='tags' is not focusable.
The plugin uses display: none; on the original field, which is a mistake I think. You can apply this CSS to have the correct validation message :
.form-tags-required {
position: absolute;
left: 0;
opacity: 0;
display: block !important;
top: 10px; // depends on your form, adapt it
}
This way, the original input can be focused and receive the "required error".
You need to write custom javascript for validation.
function validateForm()
{
var a = document.getElementById("form-tags-4").value;
if (a == "" )
{
alert("Please Fill The Required Field");
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Tags input with autocomplete:</label>
<input id="form-tags-4" name="tags-4" type="text" value="">
<button type="submit" id="save" class="btn btn-default " onclick="return validateForm()">SAVE</button>
Add form tags and add "required" on input.
<form>
<label>Tags input with autocomplete:</label>
<input id="form-tags-4" name="tags-4" type="text" value="" required>
<button type="submit" id="save" class="btn btn-default ">SAVE</button>
</form>
working fiddle
You have to add required='required' on your input first.
After that you must check during onClick event the value set and decide if it is right or wrong according to autocomplete source values.
See sample here

Categories

Resources