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.
Related
I'm performing some validation checks on some inputs from the user. I was wondering how do I check that the email entered by the user contains an # symbol and a '.' as well as characters before and after the # symbol. Thanks in advance for answering.
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
function showInput() {
var comment = document.getElementById("com").value;
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var dateOfVisit = document.getElementById("date").value;
var firstError = document.getElementById('firstNameError');
var lastError = document.getElementById('lastNameError');
var displayEl = document.getElementById('displayname');
if (!first) {
firstError.setAttribute('style', 'display: block; color: red');
} else {
firstError.setAttribute('style', 'display: none;');
}
if (!last) {
lastError.setAttribute('style', 'display: block; color: red');
} else {
lastError.setAttribute('style', 'display: none;');
}
displayEl.innerHTML =
first + " " + last + " visited this on " + dateOfVisit + " and said '" + comment || 'not a thing...' + "'";
}
</script>
<title>Great Pyramid of Giza</title>
</head>
<body>
<h2>Leave A Review!</h2>
<p>Have you been to this wonder of the world? If so, leave a review.</p>
<form>
First Name:<br>
<input type = "text" name="firstname" id="fname"><br>
<span style="display: none;" id="firstNameError">First name is required!</span>
Last Name:<br>
<input type = "text" name="lastname" id="lname"><br>
<span style="display: none;" id="lastNameError">Last name is required!</span>
Email Address:<br>
<input type = "text" name="email"><br>
Date of Visit:<br>
<input type = "text" name="date" id="date"><br>
Comment:<br>
<input type = "text" name="comment" size="70" id="com"><br>
</form>
<input type = "submit" value="Submit" onclick="showInput();">
<h2>Comments:</h2>
<p><span id='displayname'></span></p>
</body>
</html>
You can create a email input and validate against that instead of using any regex...
function isEmail(email) {
var input = document.createElement('input')
input.type = 'email'
input.value = email
return input.validity.valid
}
console.log(isEmail('admin#example.com'))
console.log(isEmail('#example.com'))
But why bother??? just use <input type="email"> and skip all javascript nonsens
<form>
<input type="text" name="firstname" required autocomplete="given-name">
<input type="text" name="lastname" required autocomplete="family-name">
<input type="email" name="email" autocomplete="email">
<input type="date" min="2018-04-21" name="date">
<textarea name="comment"></textarea>
<input type="submit">
</form>
ps, use form.onsubmit instead of btn.onclick (way better)
read more about constraint validation and inputs
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 search form on every page of my website which works perfectly, when submitting the form it goes to a page called search.php..
I have the same form also on my contact page where i also have a contact form.
the contact form does not have a submit button because i use ajax to send the post variables to a contact_process.php page. The contact form is working perfectly however on this page the search form does not work.. When I press the submit button on the search form it just refreshes the whole contact page instead of going to the search.php page. can anyone help? thanks.
The javascript and ajax for contact form:
document.getElementById('submit_message').addEventListener('click', sendMessage, false);
function sendMessage(){
$('#submit_message').removeClass("point_finger_animation");
$('#pointing_finger').fadeOut();
xmlhttp = createXHR();
xmlhttp.onreadystatechange = callback;
var not_valid_email = false;
var your_name = document.getElementById("your_name").value;
var captcha_code = document.getElementById("captcha_code").value;
var subject = document.getElementById("subject").value;
var email = document.getElementById("email").value;
var mobile_number = document.getElementById("mobile").value;
if(mobile_number.length < 10 || mobile_number.length > 14){
var not_valid_mobile = true;
}
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length){
var not_valid_email = true;
}
var message = document.getElementById("message").value;
xmlhttp.open("POST", "contact_process.php" ,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if((your_name == "" || your_name == null) || (not_valid_mobile) || (not_valid_email) || (message == "" || message == null)){
$('#container_wrapper').scrollTop(0);
document.getElementById("form_results").innerHTML = "<p>Message not sent!</p>";
if(your_name == "" || your_name == null){
document.getElementById("form_results").innerHTML = "<p>Oops! You forgot to fill in a required field!</p>";
}else if(not_valid_email){
document.getElementById("form_results").innerHTML = "<p>The email address you entered is invalid!</p>";
}else if(not_valid_mobile){
document.getElementById("form_results").innerHTML = "<p>The mobile number you entered is invalid!</p>";
}else if(message == "" || message == null){
document.getElementById("form_results").innerHTML = "<p>Oops! You forgot to fill in a required field!</p>";
}
}else{
xmlhttp.send("your_name=" + your_name + "&email=" + email + "&mobile=" + mobile_number + "&subject=" + subject + "&message=" + message + "&captcha_code=" + captcha_code);
}
}
function callback(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
refreshCaptcha();
document.getElementById("form_results").innerHTML = xmlhttp.responseText;
$('#container_wrapper').scrollTop(0);
}
}
html for contact form
<section id="form_area" class="content_box">
<div id="form_results"></div>
<form id ="contact_form" method="post" action="">
<label>Your Name (required)</label>
<input id="your_name" name="your_name" type="text" placeholder="Your Name" onfocus = "checkEnter()">
<label>Your Email (required)</label>
<input id="email" name="email" type="email" placeholder="Email" onfocus = "checkEnter()">
<label>Mobile Number (required)</label>
<input id="mobile" name="mobile" type="text" placeholder="Mobile Number" onfocus = "checkEnter()">
<label>Subject</label>
<input id="subject" name="subject" type="text" placeholder="Subject (Optional)" onfocus = "checkEnter()" >
<label>Your Message (required)</label>
<textarea id="message" name="message" rows="4" type="text" placeholder="Please leave your message here" onfocus = "checkEnter()"></textarea>
<label>Please enter the Captcha below (required). Letters are not case sensitive.</label>
<div id="captcha_wrapper">
<img id="captcha" src="/finalne2/securimage/securimage_show.php" alt="CAPTCHA Image" />
<span id="captcha_refresh"><i class="fa fa-refresh"></i></span>
</div>
<input id="captcha_code" type="text" name="captcha_code" size="10" maxlength="6" onfocus = "checkEnter()" onblur = "checkFields()"/>
<div id="submit_area">
<div id="submit_message" class="menu_level_1 button_style">Send</div>
<div id="pointing_finger"><i class="fa fa-hand-o-left"></i></div>
</div
</form><!--End of contact_form-->
</section><!--End of form_area-->
html for search form:
<div id="search_wrapper" class="menu_level_1">
<div id="search_box">
<form action="search.php" method="get">
<input id="search_content" placeholder="Search website" type="text" name="query" size="40" value="" action="" columns="2" autocomplete="off" delay="1500">
<button id="submit_search" type="submit"><i class="fa fa-search"></i></button>
<input type="hidden" name="search" value="1">
</form>
</div>
</div>
Update:
#Malk thanks for spotting the missing bracket in the closing div of the contact form :) that was indeed the problem :)
Just a guess but maybe try specifying an explicit action attribute in the contact form.
<form id ="contact_form" method="post" action="some_page_here">
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 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;
}