Javascript validation form with no alert() - javascript

Im trying to build a HTML form which will validate if a user is entering all the values in each of the input boxes. So far I've found in google examples that when the user leaves the input box blank it would call alert() which is annoying for users if they have to fill up about 10 boxes and then by accident they hit submit now they have to close 10 alerts. I was thinking if is possible to just show a red message next to the empty box(es) indicating which boxes are empty.
Here is my code showing alerts:
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" />
<input type="text" id="subject" name="subject" />
<input type="text" id="examnumber" name="examNumber" />
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
javascript:
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value==""){
msg+="You must enter your Name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if(document.ExamEntry.subject.value==""){
msg+="You must enter the Subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value=="")
{
msg+="You must enter the Examination Number \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value.length!=4)
{
msg+="Your Examination Number must be 4 characters long \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
var lvlmsg="";
for(var i=0; i < document.ExamEntry.level.length; i++)
{
if(document.ExamEntry.level[i].checked)
{
lvlmsg = document.ExamEntry.level[i].value;
break;
}
}
if(lvlmsg=="")
{
msg+="You Must Indicate Your Level";
result=false;
document.getElementById('radioButtons').style.color="red";
}
else
{
alert(lvlmsg);
}
if(msg==""){
return result;
}
else{
alert(msg);
return result;
}
}
Any ideas?

Create a span element after each input:
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"></span>
<input type="text" id="subject" name="subject" /> <span id="subject-msg"></span>
<input type="text" id="examnumber" name="examNumber" /> <span id="examnumber-msg"></span>
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
Then instead of doing this:
msg+="You Must Indicate Your Level";
Do:
var msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
And don't forget to remove alerts!

Make sure in your actual code that you are using onclick and not onlick ;)
When I am building form validations, I create a hidden inline span next to each element.
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span>Please use a valid name.</span>
<input type="text" id="subject" name="subject" /><span>Please use a valid subject.</span>
<input type="text" id="examnumber" name="examNumber" /><span>Please use a valid exam number.</span>
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
Then in your css, do something like:
input + span {
display:none;
color: red;
}
In your js remove the alerts, and add something like this for each input:
document.getElementById("[id]").style.display = "inline";

Related

How do I prevent my text area (excually input type email) from not being filled

I have form. Form include name,lastname,email,phone etc. If anybody submit the form without filling email adress my database record this email adress in blank. After this situation if this situation repeat, warning message: same email adress. (First email adress =>blank Second email adress => blank) I want to use regex. Users have to fill email adress. But I could not found any examples. Thanks to much.
Please have a look at the related code:
if (userExists.equals("")) {
bindingResult.rejectValue("email", "error.user", "Lütfen email adresinizi giriniz.");
}
if (userExists != null) {
bindingResult.rejectValue("email", "error.user", "Verilen e-postayla kayıtlı bir kullanıcı var");
}
How about some JavaScript validation code perhaps something like this which doesn't let the form actually submit if the Email field is blank:
<script type="text/javascript"> <!--
function jsValidatePg() {
// Dim var.
var strValid;
// Init.
strValid = "";
// Set var.
if (document.frmMain.Email.value == "") {
strValid = "The Email field must be filled in.";
}
// Determine if valid.
if (strValid == "") {
return true;
}
else {
alert(strValid);
return false;
}
}
//-->
</script>
<form id="frmMain" name="frmMain" action="mypage2.asp" method="post">
<input type="text" name="FirstName" size="15" maxlength="25" value="">
<input type="text" name="LastName" size="15" maxlength="25" value="">
<input type="text" name="Email" size="15" maxlength="25" value="">
<input type="text" name="Phone" size="15" maxlength="25" value="">
<input type="submit" name="btnSubmit" value="Submit" onClick="return jsValidatePg();">

Adding *Required next to an empty input

So I was wondering how I could implement required fields into my code. I tried just using required="" in the <input> tag, however, this doesn't work across all browsers. I was wondering if someone could explain how to add "* Required" next to the input if the user tries to submit and the field is empty.
Here's my form code:
contact.html
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
formvalidate.js
function validateForm()
{
var a=document.forms["Form"]["email"].value;
var b=document.forms["Form"]["subject"].value;
var c=document.forms["Form"]["message"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="")
{
alert("Please Fill All Required Field");
return false;
}
}
var input = document.getElementById('a');
if(input.value.length == 0)
input.value = "Anonymous";
First of all this is wrong:
if (a==null || a=="",b==null || b=="",c==null || c=="")
Presumably you lifted that from here and as noted in the comments, it doesn't do what it claims and will only check the last field.
To add the message you can modify your validation function to check each field and insert some text. The snippet below should give you a basic idea - and since you're new to javascript I've commented each bit with an explanation. Hope this helps:
function validateForm() {
// start fresh, remove all existing warnings
var warnings = document.getElementsByClassName('warning');
while (warnings[0]) {
warnings[0].parentNode.removeChild(warnings[0]);
}
// form is considered valid until we find something wrong
var has_empty_field = false;
// an array of required fields we want to check
var fields = ['email', 'subject', 'message'];
var c = fields.length;
// iterate over each field
for (var i = 0; i < c; i++) {
// check if field value is an empty string
if (document.forms["Form"][fields[i]].value == '') {
// create a div with a 'warning' message and insert it after the field
var inputField = document.forms["Form"][fields[i]];
var newNode = document.createElement('div');
newNode.style = "color:red; margin-bottom: 2px";
newNode.className = "warning";
newNode.innerHTML = fields[i] + ' is required!';
inputField.parentNode.insertBefore(newNode, inputField.nextSibling);
// form is now invalid
has_empty_field = true;
}
}
// do the alert since form is invalid - you might be able to skip this now
if (has_empty_field) {
alert("Please Fill All Required Field");
return false;
}
}
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
And of course you always need server side validation as well! Client side is really only to help get a snappy UIX and can be easily fail or becircumvented by any user who has a mind to do so. Any data you send to the server needs to be checked over and if something's wrong an error should be returned and handled properly on the form page.
The input field becomes a required field when you specify inside the field that it is a required field. Just placing an asterisk * or placing the word required next to it will not make it required.
Here is how to make an input field required in HTML5
Username *: <input type="text" name="usrname" required>
It is the attribute "required" of the element itself that makes it required.
Secondly.. when using the HTML5 validation you will not need javascript validation because the form will not pass the html5 validation. Having both client-side and server-side is important.

Validating multiple form fields with JavaScript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have already searched the site and while I found similar issues, I couldn't get the answer I needed, so I am asking now. I need to validate a contact form, the PHP validation is very simple but works on a base level, I want to supplement this with browser validation through JS but it is not working, the JS validation does not trigger or is not correctly coded.
I'm working on this page: http://camp-tags.com/?main_page=contact
Thanks in advance for looking for me.
The function is supposed to loop through and make sure that the 4 elements are not empty, and that both variables for phonenumber and email are formatted correctly. If any flag as false, the error is supposed to be pushed to an array and then all errors output in a single alert.
Below is the code. (updated using the tips given here. No validation at all now.)
*update: I found one glaring error I can not believe I missed. I didn't have a closing tag on the , now that is done, the form will not send unless you input the phone correct but is not validating the rest and no Alert is being issued to advise what is wrong?
JS:
function validateForm(event){
var form1 = document.getElementById("form1"),
phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/;
var errors = [];
if (phone){
event.preventDefault();
errors.push("The Phone Number is required.");
return false;
} else if (tomatch.test(phone)){
return true;
} else {
event.preventDefault();
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
return false;
}
if (name === null || name === " "){
event.preventDefault();
errors.push("The Name is required.");
return false;
} else {
return true;
}
if (email === null || email === " "){
event.preventDefault();
errors.push("The email is required.");
return false;
} else if (emailMatch.test(email)){
return true;
} else {
event.preventDefault();
errors.push("The email must be formated as follows: name#domain.com.");
return false;
}
if (address === null || address === " "){
event.preventDefault();
errors.push("The Address is required.");
return false;
} else {
return true;
}
if(errors.length > 0){
for(var i=0;i<errors.length;i++){
alert(errors)
}
return false;
} else {
return true;
}
}
html:
Send Us An Email
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="return validateForm()">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>
<script type="text/javascript" src="./assets/validation.js">
I don't know where to start from, but if you need your own validation you should remove required attribute from the inputs because FF for example will check the form instead of your validation function.
Executing event.preventDefault(); what do you think you have in event?
Properlly you should pass it when calling the function on submit and supply an argument in the function definition
onSubmit="validateForm(event);"
and function definition should be:
function validateForm(event) {
...
so you can do event.preventDefault()
...
}
You may have other problems too, but at least you will get the validation function executed and you;ll have event in it
COMPLETE EXAMPLE ADDED:
<script>
function validateForm(event) {
var phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/,
errors = [];
if (!phone){
errors.push("The Phone Number is required.");
} else if (!tomatch.test(phone)){
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
}
if (!name){
errors.push("The Name is required");
}
if (!email){
errors.push("The email is required.");
} else if (!emailMatch.test(email)){
errors.push("The email must be formated as follows: name#domain.com.");
}
if (!address){
errors.push("The Address is required.");
}
if (errors.length) {
event.preventDefault();
alert(errors.join("\n"));
}
}
</script>
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="validateForm(event)">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>

Javascript - Validation returning false when correct condition is met

Im learning Javascript and am trying to set up a basic form validation which should have the following functionality:
If error is found change text field background color to red, change field value to error message
If no errors are found, proceed
My problem
The validation is working BUT even if no errors is found it still displays an error message...what am I doing wrong?
Code follows:
function validate(){
//form validation
var name=document.getElementById("name");
var surname=document.getElementById('surname');
//name
if (name.value=='') {
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name is required"
return false;
}
else if(isNaN(name)==true){
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name: Only enter letters A-Z"
return false;
}
//surname
if (surname.value == ""){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname is required"
return false;
}
else if(isNaN(name)==true){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname: Only enter letters A-Z"
return false;
}
return true;
}
HTML
<form id="enquire" method="post">
<h2>Test Drive an Audi Today</h2>
<input type="text" id="name" value="Name" class="textbox" name="name" onfocus="if(this.value=='Name' || this.value=='Name is required' || this.value=='Name: Only enter letters A-Z' ) this.value='';" /><br />
<br />
<input type="text" id="surname" value="Surname" class="textbox" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()" />
You need to pass the value of the input fields to isNaN() like, now you are passing the dom element which will always return true since it is not a number
isNaN(name.value)
Demo: Fiddle
You should use onsubmit event of form instead of click.
<form id="enquire" method="post" onsubmit="return validate()">

OnSubmit Javascript not overriding submit action

I am trying to build a website with a webform. I am using Godaddy's default webform PHP and I am not sure how to validate the form for required fields.
I want the user to not be able to submit the form prior to validation. I found JavaScript files online submitted by other users that address this problem but I can not seem to get it to work.
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
if (email.indexOf('#') == -1) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Below is the form:
<form onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10">
</textarea><br>
<input type="submit" name="submit" value="submit"/> <span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/> <input type="hidden" name="form_delivery" value="daily"/> <input type="hidden" name="form_format" value="html"/>
I tried submitting without entering anything and it redirects me to the thank you.
form is not defined in the function. There are several ways to handle this. The simplest would be to change return checkForm() to return checkForm(this) and
function checkForm(form) {
In the form, change checkForm() to checkForm(this). Then, in your javascript, change function checkForm() { to function checkForm(form) {
Maybe this will help.
You forgot 2 thing:
first, please add name="form" into
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
second, you misstake close form, please add this code to end of HTML
</form>
Your HTML will look like:
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10"></textarea><br>
<input type="submit" name="submit" value="submit"/>
<span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/>
<input type="hidden" name="form_delivery" value="daily"/>
<input type="hidden" name="form_format" value="html"/>
</form>
1 other thing is in javascript, function to check email address is incorrect, Correct is:
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
// incorrect email address
}
New script will be:
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Goodluck!

Categories