Form validation doesn't like me - javascript

Second edit: OH MY GODS I'M AN IDIOT!!! I was focusing on the javascript and completely neglected the lack of a "result" item in the html...Thanks to those who helped!
Edit: Thanks so far. I corrected the errors that people pointed out but it still doesn't like me. :( My html is below.
I'm following a tutorial on html.net (lesson 16 on Javascript) and I've written it exactly how it's supposed to be written. I even loaded up the javascript file of the working tutorial page and compared (was the same)...then copied it and pasted it into my file just to be sure and it still doesn't work. If anyone could offer an opinion, that'd be wonderful. Code is below:
<html>
<head>
<title>Lesson 16: form validation</title>
<script type="text/javascript" src="lesson16.js"></script>
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">Name: </label>
<input type="text" id="txtName" name="txtName" />
</p>
<p><label for="txtEmail">Email: </label>
<input type="text" id="txtEmail" name="txtEmail" />
</p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
</body>
</html>
function init()
{
var myForm = document.getElementById("myForm");
myForm.onsubmit = validate;
}
onload = init;
function validate()
{
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid)
{
message = "Thank you, you know how to follow instructions...good for you.";
}
else if (! isRequiredNameSet)
{
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
}
else if (! isRequiredEmailSet)
{
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
}
else if (! isEmailValid)
{
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
function validateRequired(input)
{
var isValid = false;
if (input.length == 0)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function validateEmail(email)
{
var isValid = false;
if (email.indexOf("#") == -1 || email.indexOf(".") == -1)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function writeMessage(text)
{
var paragraph = document.getElementById("result");
if (paragraph.firstChild)
{
paragraph.removeChild(paragraph.firstChild);
}
paragraph.appendChild(document.createTextNode(text));
}

you have IsRequiredNameSet in the else if (in validate function), but it should be isRequiredNameSet.
NOTE: you can chage your validateRequired() ... to function validateRequired(input) { return !!input.length; }

The problem is the line myForm.onsubmit = validate();... where you are invoking the validate function instead os assigning it as a reference to onsubmit
myForm.onsubmit = validate;
The same applies to onload also
onload = init;
Then you have a problem in case of isRequiredEmailSet
function validate() {
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid) {
message = "Thank you, you know how to follow instructions...good for you.";
} else if (!isRequiredNameSet) {
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
} else if (!isRequiredEmailSet) {
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
} else if (!isEmailValid) {
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
Demo: Fiddle

Related

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

Why is nothing happening when I click on onclick button?

*I want to display two input fields for lower and higher number and display the necessary error messages if the inputs are wrong.
Any idea why nothing happens when I click on my button? Any way I can shorten my if-else statement cus it does feel quite wordy thank you would appreciate the comments*
<html> Enter lowest number<br>
<input type="text" id="input" size="20">
<span id="wrongInput"><br><br>
Enter highest number<br>
<input type="text" id="input2" size="20">
<span id="wrongInput2"></span><br><br>
<button type="button" onclick="testNum()">Play button</button><br><br>
</html>
<script>
function testNum()
{
//if is not a number or blank input
if (/^\d$/.test(input) == '')
{
var blank = document.getElementById("wrongInput").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input) == false)
{
var wrong = document.getElementById("wrongInput").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (/^\d$/.test(input2) == '')
{
var blank = document.getElementById("wrongInput2").innerHTML;
blank.innerHTML = "Please fill in a number";
blank.style.color ="red";
return false;
} else {
blank.innerHTML = "";
}
if (/^\d$/.test(input2) == false)
{
var wrong = document.getElementById("wrongInput2").innerHTML;
wrong.innerHTML = "Only key in number";
wrong.style.color ="red";
return false;
} else {
wrong.innerHTML = "";
}
if (input2 < input)
{
var wrong = document.getElementById("wronginput2").innerHTML;
wrong.innerHTML = "The number must be higher";
wrong.style.color ="red";
return false;
} else {
return true;
}
}
</script>
The function is called in your example, there are just a few things listed below, that I think you should consider.
First of all you are trying to call an undefined variable in all of the else-blocks.
Second, you are calling innerHTML twice in all of the if statements.
Finally you need to take a look on your conditions in the if statements.

Javascript form validation highlight invalid character

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.

Javascript Coding in HTML

For an assignment I have I am writing a registration form. My question is how would I connect the first statement, and the function below so when someone types in their email in the text box it checks to see if the email is valid? (document.getElementById('user').value)
<input id="user" type="text" onblur="isUserNameValid();"></input><br/>
function isEmailValid(email) {
"use strict";
var e = email.split("#"), local = /[^\w.!#$%&*+-\/=?^_{|}~]/, domain = /[\w.-]/;
if (e.length !== 2) {
return false;
}
if (local.test(e[0])) {
return false;
}
if (e[0].length > 253) {
return false;
}
if ((e[0][0] === ".") || (/\.\./.test(e[0]))) {
return false;
}
if (domain.test(e[1])) {
return false;
}
if (e[1].length > 253) {
return false;
}
if (e[1][0] === "." || /\.\./.test(e[1]) || e[1][e[1].length - 1] === ".") {
return false;
}
return true;
}
As you confirmed you can use HTML5, simply change your input to the below and the browser will validate the email for you when the form is submitted.
<input id="user" name="user" type="email" /><br/>
N.B. You can use a self closing tag for an input. You should also assign the name attribute of the input as that is what is used as the key for the data when it is submitted to the server.
<input type="text" id="email" name="email" onblur="javascript:return validate();"/>
<script>
function validate() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.getElementById("email").value;
if (reg.test(address) == false) {
alert('Invalid Email Address');
return false;
} else {
alert('valid Email Address');
return false;
}
}
</script>

HTML Form Validation via Javascript

I want to keep viewers from entering words like "fssadf", and force them to enter a valid email which must contain the "#" in the middle and "." to prevent spam and injection.
I also want the form to display an error message that says "change the email field to the correct email"
I use js_function.js which contain this:
function validEmail()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
but it does not prevent the viewer from sending me "sfdasfd" instead of a valid email.
What can I do to achieve the above?
check out the files below:
http://www.mediafire.com/?kx5bvttc0s2fbrs
thanks,
rami
Though I didn't see any error on my program what you provided but still you may
use
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
instead of this
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
I think that will help. I provided the total Javascript code what worked properly for me.
function validEmail()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
Use this
or you may use this too in other way
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate(this.value)" />
//Other Codes
</form>
And Javascript
<script>
function validate(email)
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
OR
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
And the last solution will be quiet easier to apply I think.
Error Message on Page instead of Popup
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
<span id="errormessage"></span>
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
document.getElementById('errormessage').innerHTML= 'fill your email';
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
document.getElementById('errormessage').innerHTML= '';
return true;
}
}
</script>
try with this
$(document).ready(function() {
$('#btn-submit').click(function() {
$(".error").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#UserEmail").val();
if(emailaddressVal == '') {
$("#UserEmail").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
});
Duplicate of this question:
Validate email address in JavaScript?
There is some valuable discussion in the comments about edge cases that SHOULD NOT be ignored.
Did you try to Google this one before you asked? IT is a /very/ common question.
If you're after a pure HTML5 solution using jQuery.... Here's a live demo
HTML
<form id="form">
Email <input name="field1" required="required" type="email" /> <br />
<div id="error"></div>
<input required="required" name="submit" type="submit" />
</form>​
Code
$(document).ready(function() {
var validCheckInput = function() {
if ($(this)[0].checkValidity()) {
$(this).removeClass("error");
$("#error").empty();
} else {
$(this).addClass("error");
$("#error").text("change the email field to the correct email");
}
if ($("#form")[0].checkValidity()) {
$("#form input[type='submit']").removeAttr("disabled");
} else {
$("#form input[type='submit']").attr("disabled", "disabled");
}
};s
var binds = function(validCheck) {
$(this).change(validCheck);
$(this).focus(validCheck);
$(this).keyup(validCheck);
validCheck.call($(this));
}
$("#form input").each(function() {binds.call(this, validCheckInput)});
});​
CSS
.error {
border: 2px solid red;
}​

Categories

Resources