I have a form that has a number of fields on it. When the user inputs anything, the field should automatically begin sending feedback as to whether or not the input is valid. The javascript code listed is suppose to handle the instantaneous feedback but it gives no reply whatsoever. It is also suppose to stop the form from being submitted if any of the user's input does not match the regular expressions. The regular expressions don't work either but they were working perfectly fine before I used the innerHTML. I would go back to using alerts if using innerHTML wasn't mandatory.
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]{5,40}$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
} else {
return valid;
}
}
function test() {
var result = true;
if (!insert()) {
result = false;
}
return result;
}
This is the html form that the javascript function is referencing.
<form name="Insert" id="I2" action="order.php" method="post" style="display: none;" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off" autofocus>Name <span id="MessNM"></span>
<br>
<input type=email id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type=password id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type=password id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type=text id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type=text id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
There are several issues I see.
You have style="display: none;" on the form which makes the whole form invisible.
Your validation function returns false on the first failed validation which means you're only going to show an error message for the first invalid field, e.g. if e-mail address and zip code are invalid you'll only get a message for e-mail address.
The regular expression for the address validation is broken.
When the password confirmation error is fixed the error message doesn't clear.
By the fact that you say it was working when you used alerts, I'm guessing the main issue you're talking about is caused by the fact that each field validation returns false. You probably just had alerts before and returned a boolean at the end of the function. Here's a solution that addresses that issue and the others I mentioned above.
<form name="Insert" id="I2" action="order.php" method="post" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off"/>Name <span id="MessNM"></span>
<br>
<input type="email" id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type="password" id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type="password" id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type="text" id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type="text" id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]*$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
return valid;
}
Related
I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.
I have this assignment in my class where we are to make a simple form with three required fields (out of five). I am having problems with getting my code to work.
This is via my professor...with what he wants
{
On submitting the form, the browser should check that :
Values for the required fields have been entered
Use regular expressions to check that the form of the entered input is proper for the email, telephone, and website fields. The forms to check for are:
Email: [alphanumeric string including . and _ ]# [alphanumeric string including . and _ ]. [alpha string]
Telephone: Either (ddd)ddd-dddd or ddd-ddd-dddd etc
Website: www.[alphanumeric string including . _ -].[com or net etc]
If any error is found, the form should not be submitted and appropriate error messages should be generated.
}
All validation must be "client side" i.e. on the browser using Javascript (not on any server and no Jquery or any programming other than Javascript and the required HTML). Use of any authoring tools is strictly and expressly forbidden.
This what I have now. Please help. Below is the code. What am I doing wrong?
<script language = "JavaScript">
<!--
function validateForm(){
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
-->
</script>
<body>
<form name="contact" action="" method="post" onSubmit = "return validateForm();">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
Try this out:- https://jsfiddle.net/vduwxjmv/
This can be done without JavaScript also using required attribute at each html control for which value is mandatory. And for clear you can use input type as reset.
HTML:-
<form name="contact" action="" method="post">
Name: <input type="textbox" name="Name" value="" required> <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value=""> <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" required> <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" required><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear" />
You can do a check by using the following JavaScript code
var result = $("#form")[0].checkValidity();
or you may change input button
<input type="submit" value="Submit Contact Details">
<!DOCTYPE html>
<html>
<body>
<form name="contact" method="post">
Name: <input type="text" class="form-control" name="Name" placeholder="Name" required="required" /> <font color = red>*Required </font><br>
Company: <input type="text" class="form-control" name="Company" placeholder="Company" /> <font color = red>Optional </font><br>
Email: <input type="email" class="form-control" name="Email" placeholder="Email" required="required" /> <font color = red>*Required </font><br>
Telephone: <input type="text" class="form-control" name="Telephone" placeholder="Telephone"/> <font color = red>Optional </font><br>
Website: <input type="text" class="form-control" name="Website" placeholder="Website" required="required" /><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"><br>
</form>
</body>
</html>
change the type from button to submit.
on giving the type as reset ,it will clear the contents.
on giving required="required", that field will be considered as a mandatory one.
<html>
<head>
<script language = "JavaScript">
function validateForm(thisVar){ alert('method Called From: ');alert(thisVar.value);alert(thisVar.name);
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
</script>
</head>
<body>
<form name="contactForm" action="" method="post" onSubmit = "return validateForm(this);">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details" onclick="validateForm(this);">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
You can validate it by two ways ---
use Submit type button
call validationForm on button click
Like --
<input type="submit" value="Submit Contact Details">
or
<input type="button" onclick="return validationForm();" value="Submit Contact Details">
you can check method call from to times 1st from onclick 2nd from onsubmit
Dont forget to appreciate (vote up).
I would like to run my page to test out whether my validation works. However, it does not work with email address. I have added regular expression for email address. It doesn't validate fully.
I entered a#live without typing .com it able to accept it. I assume this is because i type input="email" Correct me wrong. Is it due to the wrong regular expression or maybe the way I placed my code?
javascript
function validate(){
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var emailReg = '/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/';
var re = /^[\w ]+$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(email=="")
{
alert('Please fill in email fields');
return false;
}
else if(fname=="")
{
alert('Please fill in first name fields');
return false;
}
else if(lname=="")
{
alert('Please fill in last name fields');
return false;
}
return true;
}
register.php
<form name="registrationForm" method="post" id="registrationForm" class="registrationForm" action="processRegister.php" onclick="validate">
<div class='input1'>
<span id="emailAddress-label" class="help"></span>
<input class="regemailaddr" id="emailAddress" name="emailAddress" type="email" placeholder="Email Address " value="" required>
</div>
<br>
<span id="fname-label" style="margin-bottom:" class="help"></span>
<input id="fname" name="fname" type="text" placeholder="First Name " class="fname" value="" required>
<span id="lname-label" class="help"></span> <input id="lname" name="lname" type="text" placeholder="Last Name " class="lname" value="<?php echo $user_profile["lname"]; ?>" required>
<br>
<button class="greybtn" type="submit" id="submitButton">Submit</button>
<button class="cancelbtn" type="button" id="cancelButton" onclick="window.location='#';return false;">Cancel</button>
</form>
You have defined a regular expression
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
but you do not test against it
var isEmail = emailReg.test(email);
I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}
I'm trying to validate the inputs, so far I've created only two rules. One to test the phone number and another to test if the passwords entered at the same.
My problem is that for some reason my javascript isn't validating input. I have it referenced in <script>, I call it in the form onsubmit="return validate()". For some reason even with using an alert test to check that its run, that fails. So, I'm not really sure what's wrong, I could do with some extra eyes.
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var phonetest1 = true;
var phonetest2 = true;
/*get values from the form*/
var FirstName = document.getElementById("FirstName").value;
var Lastname = document.getElementById("Lastname").value;
var Email = document.getElementById("Email").value;
var Password = document.getElementById("Password").value;
var ConPassword = document.getElementById("ConPassword").value;
var Phone = document.getElementById("Phone").value;
var phonepatt1 = (/\(|0|\d|\)|\d|\d|\d|\d|\d|\d|\d|\d/);
var phonepatt2 = (/0|\d|\s|\d|\d|\d|\d|\d|\d|\d|\d/);
/* Rule one */
if (!phonepatt1.test(Phoneno)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phoneno)) {
phonetest2 = false;
}
if (phonetest1 == false && phonetest2 == false) {
errMsg += "Your Phone number is incorrect .\n";
result = false;
}
alert("I'm running"); /* This isn't working */
/* Rule two */
if (ConPassword != Password) {
errMsg += "Please confirm your password .\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result;
}
<H1>store Home Page</H1>
<p>Customer Registration: Register
<p>Customer Login: Login
<p>Manager Login Administrators
<form id="UserDetails" method="post" onsubmit="return validate()" action="index.htm">
<fieldset id="Details">
<legend>Your details:</legend>
<p>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Lastname">Last Name</label>
<input type="text" name="LastName" id="Lastname" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Email">Email</label>
<input type="text" name="Email" id="Email" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" name="Password" id="Password" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="ConPassword">Confirm Password</label>
<input type="text" name="ConPassword" id="ConPassword" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Phone">Phone Number</label>
<input type="text" name="Phone" id="Phone" maxlength="12" size="12" placeholder="(03)92251515" />
</p>
<input type="submit" value="Register Now!" />
<input type="reset" value="Reset" />
</fieldset>
</form>
You have wrog name in your JavaScript (should be Phone instead of Phoneno):
if (!phonepatt1.test(Phone)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phone)) {
phonetest2 = false;
}