I want the email field to be validated in correct format
function editAccount() {
$("#editacc").validate({
rules: {
email: {
remote: {
url: "../accounts/check-email.php?type=email",
type: "get",
data: {
email: function() {
return $( "#email" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
imeino: {
remote: {
url: "../accounts/check-email.php?type=imeino",
number: true,
type: "get",
data: {
imeino: function() {
return $( "#imeino" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
username: {
remote: {
url: "../accounts/check-email.php?type=username",
type: "get",
data: {
imeino: function() {
return $( "#username" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
mobileno: {
minlength: 10,
number: true
},
accounttype:"accountcheck"
},
messages:{
email: {
email: "Invalid Email Address",
remote: "Email ID Already registered"
},
imeino: {
remote: "IMEI No Exists",
},
username: {
remote: "Username Exists"
},
accounttype:"Imei no required for Agent",
firstname:"Firstname Required",
lastname:"Lastname Required",
mobileno:"Mobile Number Required with numbers",
email:"Email Id Required with valid format!!",
reportingstaff:"Reporting Staff Required"
},
Email is not validating in correct format.
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
}
});
/*************** check-email.php **************/
< ?php
/* check if email is already registered */
//connect to db using mysqli
if (!empty($_POST['email']))
{
$email = $mysqli->real_escape_string($_POST['email']);
$query = "SELECT ID FROM users WHERE user_email = '{$email}' LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>
Related
I have script like this:
const add_modal = $('#add_modal');
const add_form = $('#add_form');
const add_button = $('#add_button');
const save_button = $('#save_button');
let add_validator = add_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: "/admin/users/check-email",
},
role: {
required: true,
},
password: {
required: true,
minlength: 12,
},
password_verification: {
required: true,
minlength: 12,
equalTo: '#password'
},
},
messages:{
email:{
remote: "Email is already taken."
}
}
});
add_button.click(function (e) {
e.preventDefault();
add_modal.modal("show");
add_validator.resetForm();
$(':input').val("");
$("#csrf").val($csrf);
});
save_button.click(function (e) {
e.preventDefault();
let form = $(this).closest('form');
let $action = form.attr('action');
let $method = form.attr('method');
let $data = form.serialize();
if (add_form.valid()) {
$.ajax({
url: $action,
type: $method,
data:$data,
success: function (result) {
if (result.type === 'success') {
add_modal.modal("hide");
add_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});
it seems like the jqueryvalidation plugin is checking mail availability on modals open. since when I see at web inspector it sends a post request to /admin/users/check-email. how can i prevent this behaviour and make it only check when i press save_button? save_button is a button inside the modal.
Try this:
let update_validator = update_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: {
url: "/admin/users/email-available",
type: "post",
data: {
user_id: function () {
return $("#id").val();
}
}
}
},
role: {
required: true,
},
password: {
minlength: 12
},
password_verification: {
required: isPasswordPresent,
minlength: 12,
equalTo: "#update_password"
},
},
messages:{
email:{
remote: "Email is already taken."
}
},
submitHandler: function(form, event) {
event.preventDefault();
let $action = $(form).attr('action');
let $method = $(form).attr('method');
let $data = $(form).serialize();
$.ajax({
url: $action,
type: $method,
data: $data,
success: function (result) {
if (result.type === 'success') {
update_modal.modal("hide");
update_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
showCloseButton: true
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});
I am printing Badge information using below code, after print Modal box is not getting closed
$("#printCnfWithoutLoginForm").formValidation({
framework: 'bootstrap',
excluded: ':disabled',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
emailAdressWLogin: {
verbose: false,
trigger: 'blur',
validators: {
notEmpty: {
message: 'Email is Required'
},
regexp: {
regexp: /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9]{2,})+\.)+([a-zA-Z0-9]{2,4})+$/,
message: 'Please enter valid email address'
},
remote: {
type: 'POST',
url: '<?php echo get_site_url() ?>/wp-content/themes/mesocolumn/eventDetailsAjax.php/',
message: 'Sorry, You have not register for this event',
data: {
eventidWLogin: function () {
return $('#eventidWLogin').val()
},
eventtypeWLogin: function () {
return $('#eventtypeWLogin').val()
}
},
}
}
}
}
}).on('success.form.fv', function (e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
fv = $form.data('formValidation');
var data = $form.serialize();
// Use Ajax to submit form data
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: data,
success: function (data) {
var printWindow = window.open('', '', 'height=400,width=800');
var is_chrome = Boolean(printWindow.chrome);
printWindow.document.write(data);
if (is_chrome) {
setTimeout(function () { // wait until all resources loaded
printWindow.document.close(); // necessary for IE >= 10
printWindow.focus(); // necessary for IE >= 10
printWindow.print(); // change window to winPrint
printWindow.close(); // change window to winPrint
}, 400);
} else {
printWindow.document.close(); // necessary for IE >= 10
printWindow.focus(); // necessary for IE >= 10
printWindow.print();
printWindow.close();
}
}
});
$('#autoUpdate2').modal('hide');
});
You can manually called the remove() method to close the modal as
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
I am new to php and jQuery, I have googled a day but couldn't solve the problem. I want to check if the username is taken or not, but what I got is "Username is Already Taken" no matter what I enter.
so here is my code:
$(document).ready(function(){
$('#registration-form').validate({
rules: {
username: {
required: true,
minlength: 3,
maxlength: 25,
letters: true,
checkUsername: true,
},
password: {
required: true,
minlength: 6,
maxlength: 12
},
confirmpassword: {
required: true,
minlength: 6,
maxlength: 12,
equalTo: "#password"
},
email: {
required: true,
email: true
},
country:{
required: true,
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('error');
$(element).removeClass("valid");
},
success: function(element) {
element
.addClass('valid')
.closest('.form-group').removeClass('error');
}
});
$(".close, #close").click(function() {
$("label.error").hide();
$(".error").removeClass("error");
$("input.valid").removeClass("valid");
});
$.validator.addMethod("letters", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z_]+$/);
},"Letters and underscore only.");
$.validator.addMethod("checkUsername", function(value, element){
var response='';
$.ajax({
type: "POST",
url: 'checkname.php',
data:"username="+value,
async:false,
success:function(data){
response = data;
}
});
if(response == 0)
{
return true;
}
else
{
return false;
}
}, "Username is Already Taken");
});
Here is my checkname.php
<?php
include 'connect.php';
if (isSet($_POST['username'])) {
$username = mysql_real_escape_string($_POST['username']);
$check_for_username = mysql_query("SELECT * FROM user WHERE username='$username'");
if (mysql_num_rows($check_for_username)>0) {
echo "false";
} else {
echo "true";
}
}
?>
Please help me, I am so frustrated .....
You should be using the remote method, which has already been tested and proven for this exact purpose. There is no reason to reinvent something that's already been done.
rules: {
username: {
required: true,
minlength: 3,
maxlength: 25,
letters: true,
remote: { // value of 'username' field is sent by default
type: 'POST',
url: 'checkname.php'
}
}
....
Your checkname.php
include 'connect.php';
if (isSet($_POST['username']))
{
$username = mysql_real_escape_string($_POST['username']);
$check_for_username = mysql_query("SELECT * FROM user WHERE username='$username'");
if (mysql_num_rows($check_for_username) > 0)
{
echo json_encode("Username is Already Taken");
// you could even try something like this:
// echo json_encode($username . " is Already Taken");
}
else
{
echo "true";
}
}
NOTE: mysql_ has been deprecated in PHP and should be replaced with mysqli or pdo_mysql. See: php.net/manual/en/function.mysql-query.php
Also see: jQuery Validate remote method usage to check if username already exists
this is form validation, it works awesome then how to validate email pattern matching & phone no. matching. Below is my scipt part... Please Help
<script type="text/javascript">
$(window).load(function(){
$(document).ready(function () {
$('#myform').validate({
rules: {
name: {
required: true
},
email: {
required: true
},phone: {
required: true
},captcha: {
required: true
},
},
errorPlacement: function(){
return false;
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
});
});
</script>
Use this :
$(function() {
$( "#myform" ).validate({
rules: {
name: {
required: true
},
phone: {
required: true,
phoneUK: true //or look at the additional-methods.js to see available phone validations
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name."
},
phone: {
required: "Please enter your phone number."
},
email: {
required: "Please enter your email address."
}
},
});
});
</script>
Use
jQuery.validator.addMethod("foo", function(value, element) {
return this.optional(element) || /^[A-Za-z0-9\w]{4,20}/.test(value);
}, "Your entered data is not phone no");
In Function
"phone": {
required: true,
foo: true
}
See: http://jqueryvalidation.org/jQuery.validator.addMethod/
I have been scanning the interwebs for many days now, and have tried just about everything posted to resolve the issue. What i am trying to do is (like many other posts), send a remote mysql query via remote validation.. there has been much debate on the proper format of the return data (like json_encode or not) and i have tried both suggestions to no avail.
Jquery Code
$('#register-form-step-1').validate({ // initialize plugin
rules:
{
confirmEmail:
{
equalTo: "#clientEmailAddress"
},
clientPassword:
{
rangelength: [6,32],
required: true
},
clientUserName:
{
minlength: 4,
required: true,
remote:
{
async:false,
type:'POST',
url:'<?php echo base_url("home/checkusername")?>',
data: {
clientUserName: function() {
return $("#clientUserName").val();
}},
success: function(data)
{
console.log(data);
if (String(data) === String('true'))
{
//not registered
console.log("Not registered");
return true;
}
else
{
console.log(data);
//already registered
console.log("Already registered");
}
},
error: function()
{
console.log("There was an error");
}
}
},
clientEmailAddress:
{
async:false,
required: true,
email: true,
remote:
{
type:'POST',
url:'<?php echo base_url("home/checkemail")?>',
data: {
clientEmailAddress: function() {
return $("#clientEmailAddress").val();
}},
success: function(data)
{
console.log(data);
if (String(data) === String('true'))
{
//not registered
console.log("Not registered");
return true;
}
else
{
//already registered
console.log("already registered");
}
},
error: function()
{
console.log("There was an error");
}
}
}
},
submitHandler: function ()
{
$.ajax({
type: 'POST',
url: '<?php echo base_url("home/register")?>',
data: $('#register-form-step-1').serialize(),
success: function ()
{
alert('success')
console.log('form was submitted');
$("#register-form-1").modal('hide');
$("#register-form-2").modal('show');
},
error: function(data, textStatus, jqXHR) {
alert('error')
}
});
return false; // ajax used, block the normal submit
}
});
PHP CODE
public function checkemail()
{
$email = mysql_real_escape_string($_POST['clientEmailAddress']);
$qResult = $this->db->query('
SELECT clientEmailAddress FROM clientdata WHERE clientEmailAddress = "'.$email.'" limit 1
');
$result = true;
if ($qResult->num_rows == 1)
{
$result = false;
}
header('Content-Type: application/json');
echo json_encode($result);
}
Replace the line in php
echo json_encode($result);
by
echo json_encode(array($result));
and add datatype as json in js
Otherwise you can simply try
echo 1 or 0; return;
Before the line :
header('Content-Type: application/json');
Add :
header("HTTP/1.1 200 OK");
I had the same issue but finally the sample funtion did it for me.
function checkIfEmailExists($email){
$query="SELECT email FROM users WHERE email='".$email."'";
$link=#mysql_query($query);
$count=mysql_num_rows($link);
$response='';
if($count==1){
$response=false;
}else if($count==0){
$response=true;
}
header('Content-Type: application/json');
echo json_encode($response);
return;
}
}