Javascript checking if username already exists(duplicate) - javascript

I created a function that checks if the username already exists in the data list, but alert shows every time even if the username isn't in duplicate data list.
<form onsubmit="return validation()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user"></td>
<datalist id="list">
<option value="Tilen">
<option value="Marko">
<option value="Teja">
<option value="Tisa">
<option value="Rok">
<option value="Luka">
<option value="Mojca">
</datalist>
</tr>
</table>
</form>
<script>
function validation(){
var user = document.getElementById("user");
if(user.value.length <= 20 && user.value.length >= 3){
}
else{
alert("Username has to be between 3-20 characters.")
}
//duplication data list
var user = document.getElementById("user");
if(user.value == list.value){
}
else{
alert("Username already exists.")
}
}
</script>

You can get all the options using querySelector, iterate over them and compare then with user.value. Also you need list="polje_imen" in the input element.
function validacija() {
let user = document.getElementById('user');
let listOptions = document.querySelectorAll("#list option");
if (user.value.length <= 20 && user.value.length >= 3) {} else {
alert("Username has to be between 3-20 characters.")
}
for (let i = 0; i < listOptions.length; i++) {
if (listOptions[i].value === user.value) {
alert('The name already exist')
}
}
return false;
}
<form onsubmit="return validacija()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user" list="list"></td>
<datalist id="list">
<option value="Tilen">
<option value="Marko">
<option value="Teja">
<option value="Tisa">
<option value="Rok">
<option value="Luka">
<option value="Mojca">
</datalist>
</tr>
</table>
</form>
Edit: If you do not want to show the datalist, just use javascript.
function validacija() {
let user = document.getElementById('user');
let listNames = ["Tilen","Marko","Teja","Tisa","Rok","Luka","Mojca"];
if (user.value.length <= 20 && user.value.length >= 3) {} else {
alert("Username has to be between 3-20 characters.")
}
for (let i = 0; i < listNames.length; i++) {
if (listNames[i] === user.value) {
alert('The name already exist')
}
}
return false;
}
<form onsubmit="return validacija()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user"></td>
</tr>
</table>
</form>

Firstly, I don't think you're binding to the input on the datalist correctly. You can actually use the datalist as an autocomplete for the input if you simply change your input to look like this:
<input type="text" id="upor_ime" name="upor_ime" list="polje_imen">
If you have that in there, it becomes much more obvious if they choose a value that is not in the list or not from a visual perspective. Now when it comes to validating it in javascript, if you still want to take it that far, you're going to have to break out your list of possible names into an array so you can check to see if the string you're entering in the input exists in the array of strings. Because you're trying to compare an array of strings to a string, using the == operator in an if statement will not work. Here's a possible solution:
<form onsubmit="return validacija()">
<table>
<tr>
<td>Uporabniško ime:</td>
<td><input type="text" id="upor_ime" name="upor_ime" list="polje_imen"></td>
<datalist id="polje_imen"></datalist>
</tr>
</table>
</form>
<script>
var names = ["Tilen", "Marko", "Teja", "Tisa", "Rok", "Luka", "Mojca"];
var options = "";
for (let name of names) {
options += "<option value='" + name + "'>";
}
document.getElementById("polje_imen").innerHTML = options;
function validacija(){
var upor_ime = document.getElementById("upor_ime");
if(upor_ime.value.length > 20 || upor_ime.value.length < 3){
alert("Uporabniško ime mora imeti med 3-20 znakov.")
return;
}
//duplication data list
var polje_imen = document.getElementById("polje_imen");
if(names.includes(upor_ime.value)) {
alert("Uporabniško ime že obstaja.");
return;
} else{
// success
}
}
</script>
Here is a JSFiddle: http://jsfiddle.net/4f1hztr2/
Edit: I also changed around some of your if statement logic so that if the length of the item wasn't right it didn't continue executing the rest of the code.

Related

Set Attr Required when a checkbox for that field is checked

I have some looping rows which each row has a check box. And in each row there is a dropdown list which I want it to be set as required when the checkbox in the row is selected.
MARK NAME QUANTITY
---------------------------------------------------
[] inputForName1 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName2 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName3 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName4 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName5 Choose => 1,2,3,4,5
---------------------------------------------------
[SUBMIT]
(here [] is a Check-Box, and Choose => is a dropdown selection)
echo' <tr>
<td><input name="checkbox[]" type="checkbox" value="'.$i++.'" /></td>
<td><input name="items[]" type="text" value="'.$obj->items.'"></td>
echo' <td><select name="esquantity[]" required >
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
}
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
</table>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_quan=$_POST['esquantity'][$i];
mysql_query("INSERT INTO estockClaims (items,
esquantity)
VALUES ('$product_name',
'$product_quan')");
}
}
?>
The problem is when I check only two checkboxes and I submit them, it asks me to select all the dropdown list in the quantity column.
Sketch of Jquery
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('change', function(e)){
// var thisCheckbox = $(this);
var thisCheckbox = $('select[name="esquantity"]');
var thisRow = thisCheckbox.closest('tr');
if($(this.is(':checked')) {
}
.attr('required'));
}
}
</script>
I guess you didn't forget tags: <table><form> and close the input tags also <input ... />
So for your code you can try this (PHP/HTML part):
$i++;
echo' <tr>
<td><input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$i.'" onchange="enableList(this);" /></td>
<td><input name="items['.$i.']" type="text" value="'.$obj->items.'" /></td>';
echo' <td><select name="esquantity['.$i.']" id="select'.$i.'" disabled onchange="checkSelect(this)">
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
Then I've noticed in the SUBMIT part:
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $key => $i) {
$product_name=$_POST['items'][$key];
$product_quan=$_POST['esquantity'][$key];
//more code
}
}
And the Javascript part:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
if(element.checked === true){
select.disabled = false;
checkSelect(select);
}else{
select.disabled = true;
select.selectedIndex = 0;
}
}
function checkSelect(element){
if(!validate_select(element)){
element.setCustomValidity("Choose an option");
}else{
element.setCustomValidity("");
}
}
function validate_select(select){
if(select.selectedIndex === 0){
return false;
}else{
return true;
}
}
EDITED: In order to achieve the new purpose (submit only if at least one input is checked):
Add to the checkbox one class as an identifier: class="chb_group" (so you don't have to worry about other checkboxes)... and an id for the submit button maybe: id="btn_submit" and disabled by default
So you add:
function enableSubmit(){
if (document.querySelector('.chb_group:checked')) {
document.getElementById('btn_submit').disabled = false;
} else {
document.getElementById('btn_submit').disabled = true;
}
}
And call it in:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
enableSubmit();
.....
}
NOTE: This code will work only in "modern" browsers because of some functions and properties like: setCustomValidity and querySelector
That is a javascript answer. Here's the Jquery answer: http://jsfiddle.net/n13wbran/5/
You can change the req attribute which I assigned myself on checkbox change event:
$("input[name^='checkbox']").change(function () {
var id = this.name.substring(8);
if (this.checked) {
$("[name='esquantity" + id + "']").attr("req", "true");
} else {
$("[name='esquantity" + id + "']").attr("req", "false");
}
});
Then on Submit click, check the lists with req == "true" and do the following:
$("input[name='Submit']").click(function () {
var i;
for(i = 1; i <= parseInt($("[name^='esquantity']").length); i++) {
if ($("[name='esquantity[" + i + "]']").attr("req") == "true" &&
$("[name='esquantity[" + i + "]']").val() == "")
alert("Please select a value for the required lists");
}
});

Form validation linking fields as required

I am looking to do some client size validation. Below you will find an example of my template.
When this form is submitted it is okay for a line to be empty. However I want to be sure if even one item in a line is selected/has an entry that all lines will have an entry. For example. There should always be either Nothing OR require a Date, start Time, stop time, and class. (the class is populated by a button in another location) The validation will be used to warn the individual if they are missing anything and if they submit we will disregard the record as incomplete.
I have looked at jquery Validation as we are already using it on other forms in our project but, I have been unable to find a way to link row items together.
<form>
<table id="payableEventTable" class="table table-condensed table-striped">
<thead>
<tr>
<th>Date</th>
<th>Class/Scenario</th>
<th>Start</th>
<th>Stop</th>
<th>Break</th>
</tr>
</thead>
<tbody id="payableEventTableBody">
<c:forEach begin="0" end="5" varStatus="i">
<tr>
<td><input type="date" class="input-small" name="claimForm.payableEvents[${i.index}].eventDate" /></td>
<td>
<select class="classSelect" name="claimForm.payableEvents[${i.index}].event">
<option></option>
</select>
</td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStartTime" /></td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStopTime" /></td>
<td>
<select>
<option value="0" selected>No Break taken</option>
<option value="15">15 Minutes</option>
<option value="30">30 Minutes</option>
<option value="45">45 Minutes</option>
</select>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Technology we are willing to use. HTML, CSS, javaScript, jQuery, (lightweight plugins for jquery). We also have to make sure the solution works back to IE8.
Edit:
I built a JSFiddle. To help with visualization.
Edit:
I have come up with an answer. However, if anyone is able to improve on my answer, streamline it/make it look nicer I would still be willing to give out the Bounty to that person.
Here is my suggestion: To make your code more legible, you can combine the three functions validateRow(), isRowEmpty(), isRowComplete() into one simpler validateRow() function. Also it is a lot faster, because you only need to go through all elements and check their values once instead of twice.
I also created a simple to use validateForm() function to tidy things up.
The validateForm() function can now be used in an event handler:
// Event Handler
$('#validate').bind('click', function(e){
e.preventDefault();
if(validateForm()) {
alert("next");
//$('#claimWizard').wizard('next');
}
});
// Form Validation
var validateForm = function(){
var valid = true;
$('#payableEventTableBody tr').each(function() {
if (validateRow($(this))) {
$(this).removeClass("error");
}
else {
valid = false;
$(this).addClass('error');
}
});
return valid;
}
var validateRow = function(row){
var state = null,
valid = true;
row.find('input, select').each(function() {
var value = $(this).val(),
isEmpty = (value != 0 && value !== '');
//if its the first element just save the state
if(state === null) {
state = isEmpty;
}
// if this field has not the same state as the rest
else if(state !== isEmpty) {
valid = false;
}
})
return valid;
}
And here's your fiddle with my code implemented: http://jsfiddle.net/KNDLF/
So, what I came up with:
Three methods: isRowValid(), isRowEmpty(), isRowComplete()
The rows need to be either empty or complete.
//The following code is part of my logic on continuing
var valid = true;
$('#payableEventTableBody tr').each(function() {
$(this).removeClass('error');
if (!isRowValid($(this))) {
valid = false;
$(this).addClass('error');
return;
}
});
if (valid) {
$('#claimWizard').wizard('next');
}
//The following is my validation methods
<script type="text/javascript">
function isRowValid($tr) {
return (isRowEmpty($tr) || isRowComplete($tr));
}
function isRowEmpty($tr) {
var isEmpty = true;
$tr.find('input, select').each(function() {
var value = $(this).val();
if (value != 0 && value !== '') {
isEmpty = false;
}
});
return isEmpty;
}
function isRowComplete($tr) {
var isComplete = true;
$tr.find('input, select').each(function(){
var value = $(this).val();
if(value === ''){
isComplete = false;
}
});
return isComplete;
}
</script>
This should be good to start with
http://jsfiddle.net/rJaPR/
$('#validate').bind('click', function(e){
e.preventDefault();
$('#payableEventTable tr').each(function(){
var tr = $(this);
var newRowValue=0;
$(tr).find('input, select').each(function(){
var value = $(this).val();
switch(newRowValue){
case 0:
// first input/select
newRowValue = ((value!=0 && value!='') ? 1 : -1);
break;
case 1:
// there are some values in this row
if (value==0 || value=='')
tr.css('backgroundColor', 'red');
break;
case -1:
// this row should be empty
if (value!=0 && value!='')
tr.css('backgroundColor', 'red');
break;
}
})
})
})

Validating check box and input

i have a form that includes several text inputs and checkboxes (the checkboxes comes from a DB), so... i know how to validate them separetly but i need to validate them together, the way i'm doing this only validate checkboxes, i know why its happening but i don't know how to write the right way... ¿can you help me? here is the code:
<form action="sendreq.php" name="contact" onsubmit="return valida_frm(this)" method="post">
<label>Name</label>
<input name="name" type="text" />
<label>Email</label>
<input name="email" type="text"/><!-- And Severeal inputs then the checkboxes-->
<?php $list3 = mysql_query("SELECT * FROM products ORDER BY id ASC LIMIT 20");
while($row = mysql_fetch_object($list3)){ ?>
<input id="product" name="product[]" class="label" type="checkbox" value="<?php echo $row->name?>"><label class="label"><?php echo $row->name?></label>
<?php }?>
The Validation doesn't work fine its evident why, i just need the right way to write and unify the return of the alert:
function valida_frm(form){
var alerta="Ooops:\n";
if (form.name.value == "") {alerta+="Name.\n";}
if (form.email.value == "") {alerta+="Email.\n";}
for(var i = 0; i < form.product.length; i++){
if(form.product[i].checked)return true;}
alert('Oooops');
return false;
if (alerta!="Error:\n"){
alert(alerta);
return false;
}else{
return true;
}
}
Thanks for your time!
Do not call a field for "name" and then test form.name since it already has a .name
Then test form["product[]"] and not form.product - you cannot have id="product" since ID has to be unique!
I suggest you give id="product<?echo $somecounter; ?>" />...<label for="product<? echo $somecounter; ?>">...</label>
Also test against Error (or nothing as in my suggesion) and not Oops
Also more issues fixed
DEMO
function valida_frm(form){
var alerta="";
if (form.name.value == "") {alerta+="Name.\n";} // Please use FullName or such
if (form.email.value == "") {alerta+="Email.\n";}
var chks = form["product[]"],
checked = false;
for(var i = 0; i < chks.length; i++) {
if(chks[i].checked) {
checked = true;
break;
}
}
if (!checked) {
alerta+='Product.\n';
}
if (alerta){
alert("Error:\n"+alerta);
return false;
}
return true;
}

passing a javascript validation to dynamic textboxes in mvc3

Hello everyone i am working on a project similar to a shopping cart.I am using the below code to generate textboxes(for selecting the quantity) in my view:
#foreach (var item in Model)
{
<tr>
<td align="left" class="Text_nocolor">
#Html.DisplayFor(modelItem=>item.ProductName)
/td>
<td align="right" class="Text_nocolor" valign="top">
#using (Html.BeginForm("Update", "Cart", new { UserID = Request.QueryString["UserID"] }, FormMethod.Post, new { id = "myForm" }))
{
<input id="Quantity" type="text" class="Text_nocolor" name="Quantity" value="#item.Quantity" #*onblur="return NumberOnlyTextBox(event)"*# onchange="return allownumbers()" maxlength="3"/>
#Html.Hidden("unitrate", item.Rate)
<input type="submit" value="Edit" class="Text_nocolor" onkeypress="return validateNumbersOnly(e);" onclick="return RegainFocus();" />
}
In the above code "id=Quantity" represents the textboxes.
and i have written a javascript for numbers only validation for these textboxes.
These are my javascript functions:
<script type="text/javascript">
function RegainFocus() {
if ((document.getElementById("Quantity").value).length == 0) {
document.getElementById("Quantity").focus();
alert("Quantity cannot be empty");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
else if ((document.getElementById("Quantity").value) > 100) {
alert("There is no enough inventory for this product to fulfill your order");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
}
</script>
<script type="text/javascript">
function allownumbers() {
// var elements = document.getElementsByName('Quantity');
// for()
var val = parseInt(document.getElementsByName("Quantity").item(1).value);
alert(val);
if (!val || val < 1) {
alert('Please enter a valid value');
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
document.getElementById("Quantity").value = val;
return true;
}
</script>
My problem is that the validation works only for the first textbox not the others.
Can anyone pls provide a solution? Thank you
Try it using the following code snippet:
onkeypress="return validateNumbersOnly(this);" onclick="return RegainFocus(this);"
...
function RegainFocus(obj)
{
if ((document.getElementById(obj).value).length == 0) {
..
}
..
Hope it helps.

inline javascript form validation

I'm working on a form validation script at work and am having some difficulty. The form is meant to make sure that the user fills out a name, a real-looking email, a category (fromt he drop down) and a question:
This names the form and gathers all the data up from the form:
<script>
function checkForm(form1) {
name = document.getElementById("FieldData0").value;
category = document.getElementById("FieldData3").value;
question = document.getElementById("FieldData1").value;
email = document.getElementById("FieldData2").value;
This checks to see that something is in the "name" field. It works fine and validates exactly like it should, displaying the error text:
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("FieldData0").select();
document.getElementById("FieldData0").focus();
return false;
This also works just like it should. It checks to see if the email field is empty and if it is empty,displays error text and selects that field:
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
This also works just like it should, makes sure that the questions field isn't empty:
else if (question == "") {
hideAllErrors();
document.getElementById("questionError").style.display = "inline";
document.getElementById("FieldData1").select();
document.getElementById("FieldData1").focus();
return false;
}
This one works partially - If no drop down is selected, it will display the error message, but that doesn't stop the form from submitting, it just displays the error text while the form submits:
else if (category == "") {
hideAllErrors();
document.getElementById("categoryError").style.display = "inline";
document.getElementById("FieldData3").select();
document.getElementById("FieldData3").focus();
return false;
}
This one doesn't work at all no matter where I put it. I used a variation on the same script last week and it worked fine. This is supposed to check to see that the email entered looks like a real email address:
else if (!check_email(document.getElementById("FieldData1").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
Otherwise it lets the form submit:
return true;
}
This checks the email out:
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
This function hides all errors so the user isn't bombarded with red text. I tried putting in "document.getElementById("emailError").style.display = "none"" but that breaks the whole thing:
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
</script>
And the form looks like this:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<p><div class=error id=nameError>Required: Please enter your name<br/></div><p><strong>Name:</strong> <span></span><br><input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
<label for="name"></label></p>
<p><div class=error id=emailError>Required: Please enter your email address<br/></div>
<div class=error id=nameError2>This doesn't look like a real email address, please check and reenter<br/></div>
<strong><p>Email:</strong> <span>(will not be published)</span><br><input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
<label for="email"></label>
</p>
<div class=error id=categoryError>Please select a category from the drop-down menu<br></div>
<p><strong>Category:</strong> <span></span><br>
<p><select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select><label for="category"></label>
<p><div class=error id=questionError>Please type your question in the box below:<br></div><label for="question"><strong><p>Your Question:</strong> <span></span></label><br>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea></p>
<p><input type="submit" class="btn" value="Submit Question" name="Submit"></p>
</div>
</form>
Is the problem the order that I run the checks? I can't seem to figure this out. Any help would be appreciated.
I've taken the liberty to re-write your javascript to make it more readable and easier to debug.
As Marc Bernier mentioned, the dropdown element does not support the select function so I put an if statement around it to prevent an exception. I've also simplified your checkEmail function, it seemed rather convoluted. I renamed it to isAnInvalidEmail in order to make the checkForm code simpler.
You have also incorrectly named the 'emailError2' div in your HTML, which would cause another exception in the javascript. Your HTML is rather messy and, in some cases, invalid. There are missing quotes on some attribute values and missing end-tags. You should consider using the W3C validator to ensure your HTML is clean and is standards compliant.
I've hosted your code on jsbin: http://jsbin.com/iyeco (editable via http://jsbin.com/iyeco/edit)
Here's the cleaned up Javascript:
function checkForm() {
hideAllErrors();
var formIsValid =
showErrorAndFocusIf('FieldData0', isEmpty, 'nameError')
&& showErrorAndFocusIf('FieldData2', isEmpty, 'emailError')
&& showErrorAndFocusIf('FieldData2', isAnInvalidEmail, 'emailError2')
&& showErrorAndFocusIf('FieldData3', isEmpty, 'categoryError')
&& showErrorAndFocusIf('FieldData1', isEmpty, 'questionError');
/* For debugging, lets prevent the form from submitting. */
if (formIsValid) {
alert("Valid form!");
return false;
}
return formIsValid;
}
function showErrorAndFocusIf(fieldId, predicate, errorId) {
var field = document.getElementById(fieldId);
if (predicate(field)) {
document.getElementById(errorId).style.display = 'inline';
if (field.select) {
field.select();
}
field.focus();
return false;
}
return true;
}
function isEmpty(field) {
return field.value == '';
}
function isAnInvalidEmail(field) {
var email = field.value;
var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i = 0; i < email.length; i++){
if(ok.indexOf(email.charAt(i)) < 0) {
return true;
}
}
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return re.test(email) || !re_two.test(email);
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("emailError2").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
And the cleaned up HTML:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<div>
<div class="error" id="nameError">
Required: Please enter your name
</div>
<label for="FieldData0"><strong>Name:</strong></label>
<input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
</div>
<div>
<div class="error" id="emailError">
Required: Please enter your email address
</div>
<div class="error" id="emailError2">
This doesn't look like a real email address, please check and reenter
</div>
<label for="FieldData2"><strong>Email:</strong>(will not be published)</label>
<input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
</div>
<div>
<div class="error" id="categoryError">
Please select a category from the drop-down menu
</div>
<label for="FieldData3"><strong>Category:</strong></label>
<select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select>
</div>
<div>
<div class="error" id="questionError">
Please type your question in the box below:
</div>
<label for="FieldData1"><strong>Your Question:</strong></label>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea>
</div>
<input type="submit" class="btn" value="Submit Question" name="Submit">
</form>
Regarding the error on the drop-down, don't call this line:
document.getElementById("FieldData1").select();
I seem to recall having the exact same problem a few weeks ago.
First problem: move the content of that if statement into a function...then go from there. You have about 5 pieces of code doing essentially the same thing.
Next: since you're only allowing one error message at a time, create a generic div to hold it and just move the thing. That way, you don't need to keep track of hiding certain errors, displaying others, etc.
Next: only return true or false from your check_email function...returning -1 and false, etc. is bad form even though javascript is lenient on such things.
After you have cleaned up your code, it will be much easier to debug.
I would recommend getting rid of the whole if else chain and check each on individually this this.
var error = 0;
if (value == '') {
error = 1;
// other stuff;
}
if (value2 == '') {
error = 1;
// do stuff;
}
...
if (error) {
// show error
} else {
// submit form
}
Try replacing the == for === which doesn't type cast. It might help you with the dropdown problem.
Your function is returning false and it might also return -1.
As I don't know what type cast JavaScript does with !-1 you should also do this:
check_email(...)!==false;
Instead of this:
!check_email(...)

Categories

Resources