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;
}
}
Related
I am trying to verify if phone number exists in database when user fills in a number into the form field. I am using Ajax for post and return confirmation.
Everything seems fine except for an error when returning value from external file.
I am not able to pinpoint the exact error reason
The code is as follows
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
// check if input data is number
$('#phone').keyup(function(){isNumber(this);});
//Check the min chars for phone
var min_chars = 10;
//result texts
var characters_error = 'Has to be 10 digits only';
var checking_html = 'Checking...';
//when button is clicked
$('#phone').keyup(function(){
//run the character number check
if($('#phone').val().length != min_chars){
//if it's bellow the minimum show characters_error text '
$('#phone_availability_result').html(characters_error);
}else{
//else show the checking_text and run the function to check
$('#phone_availability_result').html(checking_html);
check_availabilityp();
}
});
});
//function to check phone availability
function check_availabilityp(){
//get the phone
var phone = $('#phone').val();
//use ajax to run the check
$.post("check_phone.php", { phone: phone },
function(resultp){
//if the result is 1
if(resultp == 1){
//show that the phone is available
$('#phone_availability_result').html(phone + ' is Available');
}else if (resultp == 0){
//show that the phone is NOT available
$('#phone_availability_result').html(phone + ' is not Available');
}else{//show that the phone is NOT available
$('#phone_availability_result').html('Something Wrong');}
});
};
//function to check whether input is number
function isNumber(field) {
var re = /^[0-9]*$/;
if (!re.test(field.value)) {
alert('Must be all numeric charcters. Non numerics will be removed from field!');
field.value = field.value.replace(/[^0-9]/g,"");
}
}
</script>
HTML
<input type='text' id='phone' name="phone" maxlength="10">
<div id='phone_availability_result'></div>
PHP Code 'check_phone.php'
<?php
include('connnew.php');
//$phone = mysql_real_escape_string($_POST['phone']);
$resultp = $usersdb->query("SELECT * FROM users WHERE Phone = '$phone'") or die($usersdb->error);
//if number of rows fields is bigger them 0 that means it's NOT available '
if($resultp->num_rows>0){
//and we send 0 to the ajax request
echo 1;
}else{
//and we send 1 to the ajax request
echo 0;
}
?>
I am constantly getting the error "Something Wrong". Though when I independently run the check_phone.php file, it works fine. I guess it is in the return value function that there is some error.
Maybe somebody can help identify the bug.
trim the response values before compare
$.post("check_phone.php", { phone: phone },
function(resultp){
//if the result is 1
if($.trim(resultp) == 1){
//show that the phone is available
$('#phone_availability_result').html(phone + ' is Available');
}else if ($.trim(resultp) == 0){
//show that the phone is NOT available
$('#phone_availability_result').html(phone + ' is not Available');
}else{//show that the phone is NOT available
$('#phone_availability_result').html('Something Wrong');}
});
$phone is commented in this code
$resultp = $usersdb->query("SELECT * FROM users WHERE Phone = '$phone'") or die($usersdb->error);
if($resultp->num_rows>0){
echo 1;
}else{
echo 0;
}
?>
May be you are getting response as string, Try this :
if(resultp == '1' || resultp == 1) {
//show that the phone is available
$('#phone_availability_result').html(phone + ' is Available');
}else if (resultp == '0' || resultp == 0){
//show that the phone is NOT available
$('#phone_availability_result').html(phone + ' is not Available');
}else{//show that the phone is NOT available
$('#phone_availability_result').html('Something Wrong');
}
I am using this code for validating the form input fields using ajax and jquery.... On this page : http://www.kbay.in/ajaxform/index.php
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var package_name = $('input[name=package_name]');
var comment = $('input[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (phone.val()=='') {
phone.addClass('hightlight');
return false;
} else phone.removeClass('hightlight');
if (package_name.val()=='') {
package_name.addClass('hightlight');
return false;
} else package_name.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&phone=' + phone.val() + '&package_name=' +
package_name.val() + '&comment=' + encodeURIComponent(comment.val());
But i have add a check box but dont know how to validate it using this script...any ideas....?
You could use is(":checked"):
var commentChecked = $("input[name='comment']").is(':checked'); //returns true or false
var commentVal; //define variable for storing comment value
and
if (!commentChecked) {
commentVal = "";
comment.addClass('hightlight');
return false;
} else {
comment.removeClass('hightlight');
commentVal = comment.val();;
}
And
var data = 'name=' + name.val() + '&phone=' + phone.val() + '&package_name=' +
package_name.val() + '&comment=' + encodeURIComponent(commentVal);
Add a checkbox to your HTML... something like this:
<input type="checkbox" id="ch1">
and your jQuery code to check whether it's checked or not should be like the following:
if ($("#ch1").prop("checked")) {
alert("is checked");
}
else {
alert("is not checked");
}
I am trying to use fancybox iframe to call a PHP program for payment processing from a javascript program as part of a landing page. The page also calls another PHP program that writes date to a file. I tried to simulate a click to start the fancybox function but never got it to work. I keep getting this error - $("a.hiddenclicker").fancybox is not a function. I'm not sure whether to attempt to just add this logic to the PHP file or figure out how to get fancybox to work. Here is my page. The call to fancybox is in ProcessForm().
function WriteData(url) {
var j1 = document.getElementById("hiddenclicker");
var Request2 = false;
if (window.XMLHttpRequest) {
Request2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
Request2 = new ActiveXObject("Microsoft.XMLHTTP");
}
if (Request2) {
Request2.open("GET", url, true);
Request2.onreadystatechange = function() {
if (Request2.readyState == 4 && Request2.status == 200) {
}
}
Request2.send(null);
}
}
function ProcessForm(form) {
var j1 = document.getElementById("hiddenclicker");
var firstname = "";
var lastname = "";
var payment = "";
var email = "";
var phone = "";
var donation = "";
firstname = form.firstname.value;
lastname = form.lastname.value;
email = form.email.value;
phone = form.phone.value;
donation = form.donation.value;
if (firstname == "") {
alert("You must fill in the first name");
form.firstname.focus();
return false;
}
else {
if (lastname == "") {
alert("You must fill in last name");
form.lastname.focus();
return false;
}
else {
if (email == "") {
alert("You must fill in email address");
form.email.focus();
return false; }
}
}
WriteData("writedata.php?firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&phone=" + phone + "&donation=" + donation);
if (donation == "now") {
jQuery(document).ready(function(){
$("a.hiddenclicker").fancybox(
{
'width' : 600,
'height' : 400,
'hideOnContentClick' : false,
'type' : 'iframe'
});
});
j1.href = "http://www.ccyakids.org/donation_logic/donation_start.php#form";
$('#hiddenclicker').trigger('click');
}
}
// End hiding JavaScript statements -->
HTML needed to trigger hiddenclicker
Hidden Clicker
After looking at your code you reference your link 2 different ways:
$("a.hiddenclicker") // class
$('#hiddenclicker') // ID
Which is it? Make them both the same and i am sure your problem goes away.
Hope this helps
I'm new to jQuery and have tried looking around for an answer on how to do this. I have 2 functions and I would like both to work together. The one function is submitHandler and its used to hide a form and at the same time add a class to a hidden element to unhide it - ie a thank you for submitting h1. The other function is to grab the input data and display it onsubmit in the form. So the problem is that I can get that one to work but then the other doesnt. Ie on form submit I can see the data input but not the h1 Thank you message.
Here are the functions:
SubmitHandler:
submitHandler: function() {
$("#content").empty();
$("#content").append(
"<p>If you want to be kept in the loop...</p>" +
"<p>Or you can contact...</p>"
);
$('h1.success_').removeClass('success_').addClass('success_form');
$('#contactform').hide();
},
onsubmit="return inputdata()"
function inputdata(){
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
return true;
},
The form uses PHP and jQuery - I dont know about AJAX but after some reading even less sure. Please help me out I dont know what I'm doing and at the moment I am learning but its a long road for me still.
Thank you
The form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform" onsubmit="return inputdata()">
<div class="_required"><p class="label_left">Name*</p><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><p class="label_left">E-mail address*</p><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<p class="label_left">Message</p><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<input type="submit" value="submit" name="submit" id="submit" />
</form>
The PHP bit:
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The Jquery Validate bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
Here is the full jQuery bit:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
});
});
Latest edit - Looks like this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
function submitHandler() {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
},
function inputdata() {
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
},
$(document).ready(function(){
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
});
});
I know this question has already been answered and this isn't directly regarding the question itself; more so regarding the code in the question. However, I can't post comments as I'm a brand new member, but I just thought I'd highlight a few things in your code! Mainly consistency regarding the use of jQuery.
In the function supplied for 'submitHandler' - you empty $('#content') and then append HTML to it. This will work, but an easier method would be using the .html() function; note that this function can be used to return the HTML contained inside an element; but that's when no arguments are supplied. When you supply an argument, it re-writes the content of the html element. Additionally, I would most likely use the .show() method on the h1 success element; if only for code readability.
For example:
submitHandler: function(){
$('#content').html( "<p>If you want to be kept in the loop...</p>"
+ "<p>Or you can contact...</p>");
$('h1.success_').show();
$('contactform').hide();
}
As for inputdata() - you seem to have strayed off of the jQuery ethos here a little again, I'd aim for consistency when using jQuery personally - but also as the jQuery syntax makes the traditional javascript 'document.getElemen...' object look a bit outdated/it's extra to type. At its most basic jQuery is essentially best viewed as a wrapper for the document object - just with added syntactical sugar. Additionally, it allows you to chain methods - so the last two expressions can essentially be "dressed up" to look as one when using jQuery.
I'd personally use .val(), .html() and .css() functions; example:
function inputdata(){
var usr = $('#contactname').val();
var eml = $('#email').val();
var msg = $('#message').val();
$('#out').html( usr + " " + eml + msg )
.css('display', 'block');
return true;
}
Your submitHandler function isn't called. That's why it doesn't work.
Add this to your code:
$('#contactForm').submit(function() {
inputdata();
submitHandler();
});
EDIT:
try this:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
CHange return true, to return false in the inputdata function
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
}