I'm working on a js form validation and so far I have this:
// grab form field values
var valid = '';
var name = $('form #name').val();
// perform error checking
if (name = '' || name.length <= 2) {
valid = '<p>Your name' + required +'</p>';
}
How can I validate that the user has chosen one of the options from a dropdown that I have in my form?
Thanks in advance.
$('select.foo').val();
check this
http://api.jquery.com/val/
if($('select.your-class-here').val() !== '') { //value select
} else { //nothing selected
}
Related
I've been trying to save some input to a DB using jquery. I'd like to prevent the user filling the DB with blank spaces. The code I've done so far doesn't allow to continue if the customer leaves the input box blank, which is ok. The thing is, if the customer hits the space bar more than once the record will be saved to the database. Bottom line is... I'd like to let the user keep going ONLY when he's written something into the input box. Sorry for my grammar. Hope you guys can understand. Thank you so much!
Here's the script I'm using ATM:
<script>
$(document).ready(function(){
$(function()
{
$('.btn-det').click(function(e)
{
e.preventDefault();
var name = $('#name').val();
var surname = $('#surname').val();
if (name === "" && surname === "")
{
alert("Please, enter your details!");
$("#userQuestion").hide();
}
else if(name != "" && surname === "")
{
alert("Please, enter your Surname");
$("#userQuestion").hide();
}
else if(name === "" && surname != "")
{
alert("Please, enter your Name");
$("#userQuestion").hide();
}
else {
$.post("saveDetails.php",
{
name: name,
surname: surname
});
$("#userDetails").hide(500);
$("#userQuestion").show(600);
}
});
});
});
</script>
I forgot to mention that, before saving to the DB, I have the following function which uses .trim() but it does not delete white space. It deletes only spaces at the begining and end of whatever the input is. Thanks again!
function test_input($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
In javascript you can use the trim function on a string before sending the data :
var name = $('#name').val();
name = name.trim();
http://www.w3schools.com/jsref/jsref_trim_string.asp
This will remove the blank spaces before and after the string
In php you can do the same
$name = trim((string) $_POST['name']);
Just to be clear, TRIM by default only remove spaces (not all whitespaces). Here is the doc.
UPDATE FOO set FIELD2 = TRIM(FIELD2);
http://www.w3schools.com/jsref/jsref_trim_string.asp
If you need to use trim in select query, you can also use regular expressions
SELECT * FROM table_name WHERE field RLIKE ' * query-string *'
MySql Resouces
Another Example:
UPDATE student_surveys
SET favorite_activities =
TRIM(LEADING SPACE(1) FROM TRIM(TRAILING ',' FROM favorite_activities));
use following function
trim($data," \t")
this will remove whitespaces and tabs from the beginning and end of a string.
Have a look at
http://php.net/manual/en/function.trim.php
you have to give " " as second parameter which means that remove
whitespace (i.e " ") beginning and end of a string and "\t" means remove tab. Combining both (i.e " \t") means remove space and tab.
Ok guys. This is what I did. Instead of using just an "else", I used an "else if" with the condition that none of the input fields are blank, and trimmed those at the same time... Here's just the piece I edited:
Thanks a lot for your help!
if (name === "" && surname === "")
{
alert("Please, enter your details!");
$("#userQuestion").hide();
}
else if(name !== "" && surname === "")
{
alert("Please, enter your Surname");
$("#userQuestion").hide();
}
else if(name === "" && surname !== "")
{
alert("Please, enter your Name");
$("#userQuestion").hide();
}
//If there's any data saved into the variables, it deletes any leading and trailing white spaces//
else if($.trim(name) != "" && $.trim(surname) != "")
{
$.post("saveDetails.php",
{
name: name,
surname: surname
});
$("#userDetails").hide(500);
$("#userQuestion").show(600);
Again, thank you very much!
I'm trying to make a PHP echo messages show up whenever users inputs either nothing at all or no numbers. Ive been able to make error messages show up when someone doesnt input numbers onto the text field.
However I cant make the error message I've created in PHP to show up whenever someone clicks the send button without inputing anything at all in the text field.
My PHP code:
$resurs = array();
$fyll = $_GET['inputfield'];
$dg = 2;
$nummer1 = $nummer1 * $dg;
$fel = "Fill in a number";
$nummer2 = $nummer1 * $fill;
$no = "Field is empty";
if (is_numeric($fyll)){
$resurs = array(
"nummer1" => $nummer1. "<br>",
"nummer2" => $nummer2. "<br>"
);
echo json_encode($resurs);
}
else {
$resurs = array (
"fel" => $fel. "<br>"
);
echo json_encode ($resurs);
}
if (empty($fyll)){
$resurs = array (
"no" => $no. "<br>"
);
echo json_encode ($resurs);
}
My Jquery:
$(document).ready(function(){
$("#submit1").click(function(){
var siffra = document.getElementById("inputfield");
$.getJSON("form.php?inputfield="+siffra.value, function(result){
var t1;
var t2;
var t3;
var error;
$.each(result, function(i, field){
if (i =="nummer1"){
t1 = field
}
if (i == "nummer2"){
t2 = field
}
if (i == "no"){
t3 = field
}
if (i == "fel"){
error = field
}
$(".d1").html(t1);
$(".d2").html(t2);
$(".d3").html(t3);
$(".d3").html(error);
});
});
});
});
field will be an object. You need to retrieve the properties of that object. So either, field.nummer1, field.nummer2, field.fel or field.no depending on the response from the request. Try this:
$.each(result, function (i, field) {
if (i == "nummer1")
t1 = field.nummer1;
if (i == "nummer2")
t2 = field.nummer2;
if (i == "no")
t3 = field.no;
if (i == "fel")
error = field.fel;
$(".d1").html(t1);
$(".d2").html(t2);
$(".d3").html(t3);
$(".d3").html(error);
});
Note that you're setting the value of each .dX element in each iteration of the loop, even when there is no value for the variable provided. I would suggest you check the logic of this function against your requirements.
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;
}
}
The Problem
I created a multi step form, and yes the javascript and all is already functional but i have this one problem. also the user has 2 options of navigating trough the form, either using the next button or directly clicking the steps at the header. let's say the user has a form with 3 groups, ergo he has 3 steps. In my code he can't move to step 2 when he is currently in step 1 and required fields are empty, same applies with the next button. now the problem is that if he is in step 1 and he clicks step 3 he is able to proceed to it even though there are required fields that are empty in between them. I am already at lost on how do I trap this bug.
The Format of the groups
The groups are divided by table ergo 1 group is under 1 table.
How I formatted my JS
I formatted my JS by passing 3 values to it. the first value is the current category name, the second is the category list, the third is the next category after the current.
The first value is used to check whether all the required fields are filled before moving to the next step, the array is there to hide all other categories except the third value "this is done when the user clicks the next step", while the third value is used for displaying the next step.
Preview
http://screencast.com/t/QwSVFolb
The HTML
<li>step1</li>
<li>step2</li>
<li>step3</li>
<table id ="cat1"></table>
<table id ="cat2"></table>
<table id ="cat3"></table>
The JS
function dispFields2(a, b, c)
{
var valid2;
var blanks2 = Array();
var email_reg2 = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var myVal2 = $('#'+c).find('input.required').map(function() {
return $(this).val();
}).get().join(',');
var myTitle2 = $('#'+c).find('input.required').map(function() {
return $(this).attr("title");
}).get().join(',');
var error_form2 = myVal2.split(',');
var error_title2 = myTitle2.split(',');
var errorlength2 = error_form2.length;
for(x=0;x<errorlength2;x++)
{
if(error_form2[x] == '')
{
if(myVal2 == '')
{
valid2 = true;
}
else
{
blanks2[x] = "Required - "+error_title2[x];
valid2 = false;
}
}
else
{
if(error_title2[x] == 'Email')
{
if(email_reg2.test(String(error_form2[x]).toLowerCase())==false){
blanks2[x] = error_title2[x]+" - Should be valid email";
valid2 = false;
}
}
else
{
if(blanks2 == '')
{
valid2 = true;
}
}
}
}
var requiredS2 = blanks2.toString();
var nblank2 = requiredS2.split(',').join("\n");
if(valid2 != true)
{
alert("Please review:\n\n"+nblank2);
document.getElementById(c).style.display = "";
document.getElementById(a).style.display = "none";
}
else
{
var ssplit = b.split(',');
var fieldlength = ssplit.length;
var limit;
for(i=0;i<fieldlength;i++)
{
if(a == ssplit[i])
{
limit = 1 + i;
document.getElementById(a).style.display = "";
document.getElementById("tcont").style.display = "";
document.getElementById(i).style.color = "#FF7300";
if(limit == fieldlength)
{
document.getElementById("tbutton").style.display = "";
}
else
{
document.getElementById("tbutton").style.display = "none";
}
}
else
{
document.getElementById(ssplit[i]).style.display = "none";
document.getElementById(ssplit[i]).style.color = "";
document.getElementById(i).style.color = "";
}
}
if(a == "default")
{
document.getElementById("captchas").style.display = "";
}
else
{
document.getElementById("captchas").style.display = "none";
}
}
}
Thank you.
Have the button for step 3 begin disabled, and only enable it when the user is on step 2. If the user moves back to step 1 from step 2, disable it again.
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;
}
}