pass function value to output in innerhtml div - javascript

Hi guys Im trying to pass the return value from the validation function to an innerhtml in the html section of the document. For some reason is not working.... Any help appreciated.
function validate(form) {
fail = validateName(form.name.value)
fail += validateEmail(form.email.value)
fail += validateCity(form.city.value)
if (fail == "") return true
else { alert(return document.getElementById('#errors').innerHTML=fail;}); return false}
}
function validateName(field) {
if (field == "") return "No name was entered.\n"
else if (field.length < 3) return "Name must be at least 3 characters.\n"
else if (!/[a-zA-Z ]*$/.test(field)) return "Name can only have alphabetical characters.\n"
return ""
}
function validateEmail(field) {
if (field == "") return "No email was entered.\n"
else if (!((field.indexOf(".") > 0) && (field.indexOf("#") > 0)) || /[^a-zA-Z0-9.#_-]/.test(field)) return "The email address is invalid.\n"
return ""
}
function validateCity(field) {
if (field == "") return "No city was entered.\n"
else if (field.length < 3) return "City must be at least 3 characters.\n"
else if (!/[a-zA-Z ]*$/.test(field)) return "City can only have alphabetical characters.\n"
return ""
}
<form action="<?php echo $editFormAction; ?>" name="subscribe" onSubmit="return validate(this)" id="subscribe" method="POST">
<div id="errors"></div>
<input name="name" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" type="text" id="name" placeholder="Your name"/>
<input name="email" autocomplete="off" required id="email" type="email" title="Please enter your email address" placeholder="Your email address"/>
<input name="city" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" id="city" placeholder="Your city"/>
<section id="buttons">
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">
<input type="submit" name="submit" id="submitbtn" class="submitbtn" tabindex="7" value="Submit this!">
<br style="clear:both;">
</section>

Use errors in place of #errors and remove return from alert like
if (fail == "") return true;
else {
//use innerText in place of innerHTML if #errors is not a div
document.getElementById('errors').innerHTML=fail; use errors in place of #errors
alert(fail);
return false
}

For ethical coding, you might need to avoid returning the value of a function inside the argument of a function or method:
Notice the line:
else { alert(return document.getElementById('#errors').innerHTML=fail;});
The return is passed as part of arguments of the alert().... that seems NOT okay!
This causes Syntax Errors.

Related

The id-selector does not work within php

my javascript won't respond to my id-tag within php code:
else {
echo '<form = "nav-login" method="post" onsubmit="return noEmptyUserFields();" action="includes/login.inc.php">
<input type="text" id="uidz" name="uid" placeholder="Username/e-mail">
<input type="password" id="pwdz" name="pwd" placeholder="password">
<button type="submit" name="submit">Login</button>
</form>
Sign up';
}
But it responds to my javascript which is outside of the php which looks like this:
<form class="signup-form" method="post" onsubmit="return noEmptyUserFields();" action="includes/signup.inc.php">
<input type="text" id="first" name="first" placeholder="Firstname">
<input type="text" id="last" name="last" placeholder="Lastname" >
<input type="email" id="email" name="email" placeholder="E-mail" >
<input type="text" id="uid" name="uid" placeholder="Username" >
<input type="password" id="pwd" name="pwd" placeholder="Password" ></p2>
<button type="submit" name="submit">Sign up</button></form>
How come it won't respond to the id-selector within php?
I have included <script src="includes/javascript.js"></script>
on both.
My javascript looks like this (noEmptyLoginFields) :
if (email.trim().length < 1)
{
alert('Email must be filled out');
return false;
}
else if(pwd.trim().length < 6)
{
alert('Password must contain atleast 6 characters');
return false;
}
else if (first.trim().length < 1)
{
alert('First name must be filled out');
return false;
}
else if (last.trim().length < 1)
{
alert('Last name must be filled out');
return false;
}
else if (uid.trim().length < 1)
{
alert('Username must be filled out');
return false;
}
else return true;
}
function noEmptyLoginFields()
var uidz = document.getElementById('uidz').value;
var pwdz = document.getElementById('pwdz').value;
if (uidz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
else if(pwdz.trim().length < 1)
{
alert('Username and password must be filled out!');
return false;
}
}
You seem to be using the same function name for both form validations, which is causing the error. I advise you to handle form validation purely in javascript using event handlers:
document.querySelector("#formId").addEventListener("submit", function() {
// if(...) return false;
});

JavaScript form validation (check for all letters only)

I'm trying to create one function that will check that a field is not blank, contains only letters and spaces. Validating that the field contains letters and spaces only does not appear to work as anything that's put in the field will return the alert message.
I'm trying to say:
If the name field is NOT letters and spaces then display this alert "...". Else return true.
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (x!==/^[A-Za-z ]+$/) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
else {
return true;
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
missing } at end of script and missing ; at else if
and use regex for check only letter and space
function validateForm() {
var regex = new RegExp("^[a-zA-Z ]+$");
var x = document.forms["newsletterForm"]["name"].value;
if (x == null || x == "") {
alert("Name must not be blank");
return false;
} else if (!regex.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)");
return false;
} else {
return true;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
Hi You can use regex for that
var regexExp = /^[a-zA-Z\s]*$/;
function validateForm() {
var x = document.forms["newsletterForm"]["name"].value;
alert(x)
if (x==null || x=="") {
alert("Name must not be blank");
return false;
}
else if (!regexExp.test(x)) {
alert("Name contains invalid characters (letters and spaces only!)")
return false;
}
}
<form name="newsletterForm" action="#" onsubmit="return validateForm()" method="post">
<label for="name">Name*: </label><br>
<input type="text" name="name" placeholder="Fill in your name"1> <br><br>
<label for="email">E-mail*: </label><br>
<input type="text" name="email" placeholder="Fill in your e-mail address"><br><br>
<label for="comments">Comments (optional): </label> <br>
<textarea rows="5" cols="20" name="comments" placeholder="Leave us a message"></textarea><br>
<input type="submit" value="Submit">
</form>
I'm thinking that the problem is your use of !==. !== would be looking for an absolute match between x and your regular expression object - that is, is x that regular expression object; not does it match that expression.
What about this:
else if (! /^[A-Za-z ]+$/.test(x))
use typeof
try
if(x == null || typeof x !== 'string')
{
//code here
}
An empty string isn't a valid value to check against.

Custom Error Messages in HTML5 Required Form Fields

I've made a form with required fields and custom error messages/validation, which all display/work correctly, however if the error is corrected, the form still cannot be submitted. This was working before I added the inline oninvalid checks. Not sure what I'm doing wrong.
Code:
<form role="form" method="post" action="contact-form.php">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="this.setCustomValidity ('Please enter your name.')" />
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required />
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="this.setCustomValidity ('Please enter your message.')"></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl" />
</form>
<script>
var email = document.querySelector( "#email" );
function setErrorMessage() {
if ( email.validity.valueMissing ) {
email.setCustomValidity( "Please enter your email address." );
} else if ( email.validity.typeMismatch ) {
email.setCustomValidity( "Please enter a valid email address." );
}
};
setErrorMessage();
email.addEventListener( "change", setErrorMessage );
</script>
JSFiddle: http://jsfiddle.net/44Lrgmjc/
Any help would be greatly appreciated!
Thanks.
I adjusted your javascript and added (key) a validate email function. here is a fiddle
function validate{
function email(){
if(form.email.value == "") {
alert("Please enter your email");
form.email.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if(!re.test(form.email.value)) {
alert("Invalid email address");
form.email.focus();
return false;
}
// validation was successful
return true;
}
function name(){
If(form.name.value == "") {
alert("Please enter your name");
form.name.focus();
return false;
}
// validation was successful
return true;
}
function msg{
if(form.message.value == "") {
alert("Please enter your message");
form.message.focus();
return false;
}
// validation fails if the input doesn't match our regular expression
if(!re.test(form.message.value)) {
alert("Invalid message content");
form.message.focus();
return false;
}
// validation was successful
return true;}}
</script>
<script>
function validateEmail()
{
var emailID = document.form.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.form.email.focus() ;
return false;
}
return( true );
}
<form role="form" method="post" action="contact-form.php" onsubmit="return validate(this);">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="alert ('Please enter your name.')"/>
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required oninvalid="alert ('Please enter a valid email.')"/>
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="alert ('Please enter your message.')" ></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl"/>
</form>
Reference

Validation through getElementById()

I'm been trying to validate my fields by using 'getElementById()' with '.value'. However, it seems like either getElementById.value is not working or some codes has overlap the function.
Updated Javascript function:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("Don leave blank!")
return false;
}
if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("invalid");
return false
}
return true; //doesn't go to next.php
}
My Form:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>
I have already defined my onclick function to my Javascript and tried to add return false too. But the alert still cant appear. Kindly advise.
Your markup is invalid:
<input name="Name" type="text" id="Name" " value=""/>
^-----------should be removed
so correction would be removing all extra " characters:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
For preventing submition,when input is invalid, you can try something like a:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
alert("Correct")
else {
alert("Don leave blank!")
return false;
}
if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
alert("Correct")
else {
alert("invalid");
return false;
}
}
//Borrowed from jQuery lib
function isNumeric( obj ){
return !isNaN( parseFloat(obj) ) && isFinite( obj )
}
<input type="submit" name="submit" onclick="return validate()"/>
Try this,
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") {}
else {alert("Don leave blank!"); return false;}
if (isNaN(Tel)){ alert("invalid"); return false;}
else { }
return true;
}
Your HTML submit button code should be
<input type="submit" name="submit" onclick="return validate()"/>
Use return false to prevent submitting form in case of any validation errors.

Multiple Validation checks - logic error

I am providing a validation feature on a form for passwords. I need to be able to implement a few validation rules and have them all checked on submit. Now to me the code is sound but I think they may be some logic error in my code that I'm too tired to notice (too the coffee machine!)
Here's the JavaScript:
<script type="text/javascript">
<!--
function validate(registerForm)
registerForm.onsubmit=function()
{
var pw1 = document.forms["register"]["password1"].value;
var pw2 = document.forms["register"]["password2"].value;
//Check values are present in both fields
if(pw1 == '' || pw2 == '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 != pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
//Accept passwords
{
alert("Password accepted!");
return true;
}
}
}
-->
</script>
And the HTML Form to go with it:
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" value="Register" />
</form>
<script type="text/javascript">
<!--
new validate(document.forms['register']);
-->
</script>
Any ideas of lovely StackOverflow community? The exact problem is that it won't check for spaces in passwords or whether two passwords entered are the same. It successfully checks that there is at least something in both password fields.
Thanks Dan
This line:
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
invalid is not defined and I suspect this will cause the problems you're facing.
Made changes to your code got it working http://jsbin.com/igonec/edit#preview
ERRORS
Use of var pw1 = document.forms["register"]["password1"]. It was causing errors
Missing else.
Use of invalid instead of " ".
Wrong use of brackets.
I omitted your errors and made the solution more elegant.
Javascipt
function validate()
{
var pw1 = document.getElementById("password1").value;
var pw2 = document.getElementById("password2").value;
//Check values are present in both fields
if(pw1 ==='' || pw2 === '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.getElementById("password1").value.indexOf(" ") > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 !== pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
else
{
alert("Password accepted!");
return true;
}
}
}
HTML
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" onclick="validate()" value="Register" />
</form>

Categories

Resources