jQuery confirm box - php

I have a loop that runs through checking boxes for input, if everything returns okay, it needs to show a popup box asking the user if it is okay to carry on and submit their order, and if not then it needs to do nothing (handled within)
I've come across a few problems and can't figure out how to do it, any ideas?
Here's my current code
function validateSubmit(){
var r=true;
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
var qty1 = input1.val();
// Find Second input
var input2 = $(this).find('input').eq(1);
var qty2 = input2.val();
// Find third input
var input3 = $(this).find('input').eq(2);
var qty3 = input3.val();
// Find select box
var selectBx = $(this).find('select');
var selectVal = selectBx.val();
if(qty1 === '' && selectVal != 'Please Select...') {
alert("You've chosen an option, but not entered a quantity to dispute, please check your inputs.");
r=false;return false;
}
if(qty1 != '' && selectVal === 'Please Select...') {
alert("You've entered a quantity, but not chosen why, please check your reasons.");
r=false;return false;
}
if (qty1 > qty2) {
alert("For one of your entries, the disputed quantity is larger than the shipped quantity.");
r=false;return false;
}
});
if (r==true) {
var a = confirm("Are you sure you want to confirm the dispute? You cannot edit this after it's been submitted?");
if (a==true)
{
return true;
}
else
{
return false;
}
}
});
HTML:
<table>
<thead>
<tr><th>Item ID</th><th>Description</th><th>Dispute Quantity</th><th>Shipped Quantity</th><th>Ordered Quantity</th><th>Reason</th></tr>
</thead>
<tbody>
<?php
$data = mysql_query("SELECT * FROM `artran09` WHERE `invno` = '$invoiceno'") or die(mysql_error());
echo "<center>";
$i = -1;
echo "<form action=\"submitdispute.php?invno=".$invoiceno."&ordate=".$placed."\" method=\"POST\" onsubmit=\"return validateSubmit();\">";
while ($info = mysql_fetch_array($data)) {
$i += 1;
echo "<tr>";
echo "<td>".$info['item']."</td>";
echo "<td>".$info['descrip']."</td>";
echo "<td><input type=\"text\" input name=".$i." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyshp']." name = \"ship$i\" onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyord']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><select name = \"reason$i\">";
echo "<option>Please Select...</option>";
echo "<option>Short/Not received</option>";
echo "<option>Damaged Goods</option>";
echo "<option>Product Not Ordered</option>";
echo "</select></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
<p><input type = "submit" value = "Dispute" name ="Submit">
</form>
For anyone interested - I have fixed this!
Thank you for everyone's patience! Here's the fix:
function validateSubmit(){
var r=true;
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
var qty1 = input1.val();
// Find Second input
var input2 = $(this).find('input').eq(1);
var qty2 = input2.val();
// Find third input
var input3 = $(this).find('input').eq(2);
var qty3 = input3.val();
// Find select box
var selectBx = $(this).find('select');
var selectVal = selectBx.val();
if(qty1 === '' && selectVal != 'Please Select...') {
alert("You've chosen an option, but not entered a quantity to dispute, please check your inputs.");
r=false;return false;
}
if(qty1 != '' && selectVal === 'Please Select...') {
alert("You've entered a quantity, but not chosen why, please check your reasons.");
r=false;return false;
}
if (qty1 > qty2) {
alert("For one of your entries, the disputed quantity is larger than the shipped quantity.");
r=false;return false;
}
});
if (r=true) {
var a = confirm("Are you sure you wish to dispute? You cannot dispute this order again once submitted.");
return a;
}
}
Help massively appreciated!

Answer:
function validateSubmit(){
var r=true;
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
var qty1 = input1.val();
// Find Second input
var input2 = $(this).find('input').eq(1);
var qty2 = input2.val();
// Find third input
var input3 = $(this).find('input').eq(2);
var qty3 = input3.val();
// Find select box
var selectBx = $(this).find('select');
var selectVal = selectBx.val();
if(qty1 === '' && selectVal != 'Please Select...') {
alert("You've chosen an option, but not entered a quantity to dispute, please check your inputs.");
r=false;return false;
}
if(qty1 != '' && selectVal === 'Please Select...') {
alert("You've entered a quantity, but not chosen why, please check your reasons.");
r=false;return false;
}
if (qty1 > qty2) {
alert("For one of your entries, the disputed quantity is larger than the shipped quantity.");
r=false;return false;
}
});
if (r=true) {
var a = confirm("Are you sure you wish to dispute? You cannot dispute this order again once submitted.");
return a;
}
}

Related

Autocomplete Box Only Shows First Letter

I am trying to make a text box that when you type in it, it pulls up suggestions underneath that come from a recordset. For some reason when you type in the field, I only get the first letter. It think it has to do with the json_encode part. When I changed the array to be just text: "Brainpop","Google", etc. it worked fine. Any thoughts? This is the coding I based it off of:
https://www.w3schools.com/howto/howto_js_autocomplete.asp
<script type="application/javascript">
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}</script>
<script>
//now put it into the javascript
var software_list = <?php echo json_encode($types2, JSON_UNESCAPED_SLASHES), "\n"; ?>;
</script>
<?php
$query1 = "SELECT software_name from software";
$result = mysqli_query($sdpc_i, $query1);
$types = array();
while ($row = $result->fetch_assoc()) {
$types[] = '"'.$row['software_name'].'"';
}
$types2 = implode(",",$types);
?>
<div class="autocomplete"><input type="text" name="software_name" id="myInput" class="form-control col-md-8" value="" required></div><script>
autocomplete(document.getElementById("myInput"), software_list);
</script>
</div>

jQuery - query doesn't stop after return false is used

I'm having a problem... when a user clicks submit - the error message shows, but the jQuery doesn't seem to stop on Return False;
See code below:
function validateSubmit(){
// this will loop through each row in table
// Make sure to include jquery.js
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
var qty1 = input1.val();
// Find Second input
var input2 = $(this).find('input').eq(1);
var qty2 = input2.val();
// Find third input
var input3 = $(this).find('input').eq(2);
var qty3 = input3.val();
// Find select box
var selectBx = $(this).find('select');
var selectVal = selectBx.val();
if(qty1 === '' && selectVal != 'Please Select...') {
alert("You've chosen an option, but not entered a quantity to dispute, please check your inputs.");
return false;
}
if(qty1 != '' && selectVal === 'Please Select...') {
alert("You've entered a quantity, but not chosen why, please check your reasons.");
return false;
}
if (qty1 > qty2) {
alert("For one of your entries, the disputed quantity is larger than the shipped quantity.");
return false;
}
});
}
HTML where it's called
<table>
<thead>
<tr><th>Item ID</th><th>Description</th><th>Dispute Quantity</th><th>Shipped Quantity</th><th>Ordered Quantity</th><th>Reason</th></tr>
</thead>
<tbody>
<?php
$data = mysql_query("SELECT * FROM `artran09` WHERE `invno` = '$invoiceno'") or die(mysql_error());
echo "<center>";
$i = -1;
echo "<form action=\"submitdispute.php?invno=".$invoiceno."&ordate=".$placed."\" method=\"POST\" onsubmit=\"return validateSubmit();\">";
while ($info = mysql_fetch_array($data)) {
$i += 1;
echo "<tr>";
echo "<td>".$info['item']."</td>";
echo "<td>".$info['descrip']."</td>";
echo "<td><input type=\"text\" input name=".$i." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyshp']." name = \"ship$i\" onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyord']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><select name = \"reason$i\">";
echo "<option>Please Select...</option>";
echo "<option>Short/Not received</option>";
echo "<option>Damaged Goods</option>";
echo "<option>Product Not Ordered</option>";
echo "</select></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
<p><input type = "submit" value = "Dispute" name ="Submit">
</form>
Any ideas?? Help massively appreciated
The return currently will leave the each(), not validateSubmit() (validateSubmit currently doesn't return anything)
Define a variable at the begin of validateSubmit(), e.g.
var r=true;//default returnValue
and put this at the end of validateSubmit():
return r;
Now, when you want to leave validateSubmit() , call inside the each:
r=false;return;
This will leave the each() and also validateSubmit() with the returnValue r(what will be false now)
Add a preventDefault call to your code. Change the line:
function validateSubmit(){
to the following
function validateSubmit(e){
e.preventDefault();
...
Ensure that your button uses 'return' also to return the returned value:
<input type="submit" onClick="return validateSumbit();" />
Also you should remove the onsubmit handler from the form tag.
Your validateSubmit() function doesn't seem to return a value. Only the callback function of the each() method returns a value, but your actual submit handler does not. In essence, your validation code runs as expected, displaying the error messages but not returning any value to indicate of failure.
You should define a variable within the scope of validateSubmit() which the each() method can modify and return that.
For example:
function validateSubmit() {
var form_is_valid = true;
$('tr').each( function() {
// Validation goes here
if (something_is_invalid) {
form_is_valid = false;
return;
}
});
return form_is_valid;
}

Checking one field against another using jQuery

I have come about quite a problem while programming an order submitting page, the aim of the page is to submit a dispute for an order - providing two fields are filled in, but only if one field is less than another one.
Basically, one is a drop down and the other is a disputes box, the queries are as follows:
If DisputesTextBox = "" and a drop down box = "Please Select..."
Everything is fine - submit button enabled
If DisputesTextBox != "" and dropdown box = "Please select..."
Error ( and vice versa, so if disputes is populated but dropwn = please select...) - submit button disabled
If DisputesTextox != "" and dropdown box = "Other"
Everything is fine - submit button enabled
If DisputesTextBox > shippedbox
Error - submit button disabled
<table>
<thead>
<tr><th>Item ID</th><th>Description</th><th>Dispute Quantity</th><th>Shipped Quantity</th><th>Ordered Quantity</th><th>Reason</th></tr>
</thead>
<tbody>
<?php
$data = mysql_query("SELECT * FROM `artran09` WHERE `invno` = '$invoiceno'") or die(mysql_error());
echo "<center>";
$i = -1;
echo "<form action=\"submitdispute.php?invno=".$invoiceno."&ordate=".$placed."\" method=\"POST\" onsubmit=\"return confirm('Are you sure you are ready to dispute your order?');\">";
while ($info = mysql_fetch_array($data)) {
$i += 1;
echo "<tr>";
echo "<td>".$info['item']."</td>";
echo "<td>".$info['descrip']."</td>";
echo "<td><input type=\"text\" input name=".$i." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyshp']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyord']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><select name = \"reason$i\">";
echo "<option>Please Select...</option>";
echo "<option>Short/Not received</option>";
echo "<option>Damaged Goods</option>";
echo "<option>Product Not Ordered</option>";
echo "</select></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
<p><input type = "submit" value = "Dispute" name ="Submit">
</form>
Thanks, hope anyone can help!
Edited for Wolf/anyone who can help - what's up with this code here:
-- code i edited --
function validateSubmit(){
// this will loop through each row in table
// Make sure to include jquery.js
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
var qty1 = input1.val();
// Find Second input
var input2 = $(this).find('input').eq(1);
var qty2 = input2.val();
// Find third input
var input3 = $(this).find('input').eq(2);
var qty3 = input3.val();
// Find select box
var selectBx = $(this).find('select');
var selectVal = selectBx.val();
// Add your validation code here for the inputs and select
// Return true if all validations are correct
// Else return false
if(qty1 = "" && selectVal = "Please Select...") {
return true;
alert("You have an error somewhere, please check over your quantites.");
break;
}
if (qty1 > qty2) {
return false;
alert("You have an error somewhere, please check over your quantites.");
break;
}
});
}
Change the following line
onsubmit=\"return confirm('Are you sure you are ready to dispute your order?');\"
to
onsubmit=\"return validateSubmit();\"
Then write the function
function validateSubmit(){
// this will loop through each row in table
// Make sure to include jquery.js
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
// Find Second input
var input2 = $(this).find('input').eq(1);
// Find third input
var input3 = $(this).find('input').eq(2);
// Find select box
var selectBx = $(this).find('select');
// Add your validation code here for the inputs and select
// Return true if all validations are correct
// Else return false
});
}
Note that your submit button will be enabled all the time. But submit will work only if your validations are success.

Javascript alert box and confirmation after

I want to create a javascript for checking value of textbox so if the textbox blank, it won't proceed to next page. AND after checking (if all condition is true) it will return the result of textbox.
I've created this javascript:
function cekdata(myform)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (document.myform.clientid.value == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
return false;
}
else
if (document.myform.nama.value == "")
{
alert("Please Fill Passenger Name");
myform.nama.focus();
return false;
}
else
if (document.myform.lokasi.value == "")
{
alert("Please Fill Origin Location");
myform.lokasi.focus();
return false;
}
else
if (document.myform.tujuan.value == "")
{
alert("Please Fill Your Destination");
myform.tujuan.focus();
return false;
}
else
if (document.myform.tglb.value == "")
{
alert("Please Fill Departure Date");
myform.tglb.focus();
return false;
}
else
if (document.myform.novehicle.value == "")
{
alert("Please Fill Vehicle Number");
myform.novehicle.focus();
return false;
}
else
if (document.myform.driverid.value == "")
{
alert("Please Fill Driver ID");
myform.driverid.focus();
return false;
}
else
if(document.getElementById('twoway').checked)
{
if (document.myform.tglp.value == "")
{
alert("Please Fill Return Date");
myform.tglp.focus();
return false;
}
else
if (document.myform.tglb.value > document.myform.tglp.value)
{
alert("Return date must bigger than departure date");
myform.tglp.focus();
return false;
}
}
else
{
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
if (a==true)
{
return true;
}
else
{
return false;
}
}
}
And I called this function like this:
<form name="myform" onsubmit="return cekdata(this);" method="POST" action="<?php $_SERVER["PHP_SELF"]; ?>">
But what I got is the confirm box never show up, and it returns true (and go to next page). So, how to change this condition so my confirmation box showed up first, then after click OK, it go to next page, and if CANCEL, do nothing?
*Just make slight changes in your javascript just passevent on form submit*
<input type="submit" value="Submit" name="submit" onClick="return cekdata(this,event);" />
and when your textbox is empty or null write event.preventDefault() instead of return false;
function cekdata(myform,evt)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (document.myform.clientid.value == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
evt.preventDefault();
}
Try this:
Remove your last else part and paste below lines at the end of your javascript function.
Remove below lines :
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
instead use this,
var a = window.confirm("Are you sure?");
if (a==true)
{
return true;
}
else
{
return false;
}
I would better suggest you to place that cekdata(this) in your submit tag rather than form tag. Like
<input type="submit" value="Submit" name="submit" onClick="return cekdata();" />
And also when you have done this
var id = document.myform.clientid.value;
Then why you are using again the same
if (document.myform.clientid.value == "")
Better use
var id = document.myform.clientid;
if (id.value == "")
{
alert("Please Fill Your ID");
id.focus();
return false;
}
Changing code like this:
function cekdata(myform)
{
var id = document.myform.clientid.value;
var nama = document.myform.nama.value;
var divisi = document.myform.divisi.value;
var way = document.getElementById('twoway').value;
var ori = document.myform.lokasi.value;
var desti = document.myform.tujuan.value;
var ket = document.myform.keterangan.value;
var tpergi = document.myform.tglb.value;
var jpergi = document.myform.jamb.value;
var mpergi = document.myform.menitb.value;
var pegi = tpergi+', '+jpergi+':'+mpergi;
var tplg = document.myform.tglp.value;
var jplg = document.myform.jamp.value;
var mplg = document.myform.menitp.value;
var plg = tplg+', '+jplg+':'+mplg;
if (id == "")
{
alert("Please Fill Your ID");
myform.clientid.focus();
return false;
}
else
if (nama == "")
{
alert("Please Fill Passenger Name");
myform.nama.focus();
return false;
}
else
if (ori == "")
{
alert("Please Fill Origin Location");
myform.lokasi.focus();
return false;
}
else
if (desti == "")
{
alert("Please Fill Your Destination");
myform.tujuan.focus();
return false;
}
else
if (tpergi == "")
{
alert("Please Fill Departure Date");
myform.tglb.focus();
return false;
}
else
if(document.getElementById('twoway').checked)
{
if (tplg == "")
{
alert("Please Fill Return Date");
myform.tglp.focus();
return false;
}
else
if (tpergi > tplg)
{
alert("Return date must bigger than departure date");
myform.tglp.focus();
return false;
}
}
else
{
var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg);
if (a==true)
{
return true;
}
else
{
return false;
}
}
}
then it works...
I would recommend using Jquery insead of Javascript.
Here is the short & sweet code I have made just for you, feel free to use it!
JQUERY CODE
$(document).ready(function() {
$('#submit').click(function(){
var id = $('#id').val();
var dataString = 'id='+ id;
if(id==''){
alert("Please Fill Your ID");
$('#id').focus();
return false;
}
else if(confirm("Are you sure? Your id = "+id))
{
$.ajax({
type: "POST",
url: "ajxRegistration.php",
data: dataString,
cache: false,
success: function(e)
{
e.stopImmediatePropagation();
}
});
return false;
}
});
})
Try this -
if(confirm('Are you sure?'))
return true;
else
return false;

email validation jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery validate e-mail address regex
hi i have an input filed in a form referencing to an email input field , and when the user clicked the submit button i want to ensure that the email input field value has the formal like this
example#hotmail.com
or
example#gmail.com
or
example#yahoo.com
and the input field is this
<p>
<label>Email</label>
<input type="text" name="Email"/>
<span class="errorMessage"></span>
</p>
jquery code
$(document).ready(function(){
$('#suform').on('submit', function(e){
e.preventDefault();
var errorCount = 0;
$('span.errorMessage').text(''); // reset all error mesaage
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
var error = 'Please fill ' + $this.prev('label').text(); // take the input field from label
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
if(errorCount === 0){
var mobileNumber = $('input[name=MNumber]');
var email = $('input[name=Email]');
if(isNaN(parseFloat(mobileNumber )) && !isFinite(mobileNumber )) {
var error = 'Mobile number incorect.';
$('input[name=MNumber]').next('span').text(error);
errorCount = errorCount + 1;
}else{
var password= $('input[name="Password"]').val();
var repass= $('input[name="RePassword"]').val();
if(password!=repass){ // ensrue the two passwords are the same
var error2 = 'Password not matching';
$('input[name="RePassword"]').next('span').text(error2)
errorCount = errorCount + 1;
}else{
$(this)[0].submit(); // submit form if no error
}
}
}
});
});
my html , css and jquery code is here
code
If I understand you correctly, you want to validate the email address filled on the form:
ADD TO YOUR FUNCTION
// validate proper email address
var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
if (reg.test(value) == false) {
// email invalid, do stuff
} else {
// email valid, do stuff
}
This Regular expression checks the email provided for many many many issues!
EDITED:
You're function had some typos, here it is fully functional: and a working Fiddle!
$(document).ready(function(){
// form submit
$('#suform').on('submit', function(e){
// prevent default behavior
e.preventDefault();
// reset errors counter
var errorCount = 0;
// clear error message
$('span.errorMessage').text('');
// run by each input field to check if they are filled
$('input').each(function(){
var $this = $(this);
if($this.val() === ''){
// take the input field from label
var error = 'Please fill ' + $this.prev('label').text();
$this.next('span').text(error);
errorCount = errorCount + 1;
}
});
// no errors so far, let continue and validate the contents
if(errorCount === 0){
// get mobile number
var mobileNumber = $('input[name=MNumber]').val();
// get email address
var email = $('input[name=Email]').val();
// get password and password repeat
var password= $('input[name="Password"]').val();
var repass= $('input[name="RePassword"]').val();
// regular expression to validate the email address
var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
// try to validate the email
if (reg.test(email) == false) {
$('input[name=Email]').next('span').text('Email address is invalid!');
errorCount = errorCount + 1;
} else {
if(isNaN(parseFloat(mobileNumber )) && !isFinite(mobileNumber )) {
var error = 'Mobile number incorect.';
$('input[name=MNumber]').next('span').text(error);
errorCount = errorCount + 1;
} else {
// ensrue the two passwords are the same
if(password!=repass){
var error2 = 'Password not matching';
$('input[name="RePassword"]').next('span').text(error2);
errorCount = errorCount + 1;
}else{
$(this)[0].submit(); // submit form if no error
}
}
}
}
});
});
Regular expression is one way to validate :
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Pass a user entered email to this function it will check its formate and return true or false accordingly
You can use this function:
function validateEmail(email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( email ) ) {
return false;
} else {
return true;
}
}

Categories