i have a file input box which is not required for validation. But if the input box is not empty then i want the validation for file type and file size to be executed.
jQuery(document).ready(function(){
jQuery.validator.addMethod("accept", function(value, element, param) {
return value.match(new RegExp("." + param + "$"));
});
jQuery.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
});
jQuery('#adminform').validate({
rules: {
resume: {
required: false,
accept: "(doc|docx|pdf)",
filesize: 1024 //1048576
}
},
......................
resume: {
accept: "File type not supported",
filesize: "File cannot be more than 1MB!"
},
For now the problem is that even if i don't supply any input and leave it empty, i get the rule "accept" executed i.e i get the message "File type not supported".
Try this..Not empty check ensures that if field is left blank then validation won't be performed
$('input[type="file"]').on("change", function() {
if ($this.val() !== '') {
//do validation stuff here!!
}
});
Tryout this if this helps:
$("#commentForm").validate({
rules: {
name: "required",
file: "required",
name: {
required: true,
minlength: 2
},
file: {
required: false,
minlength: 5
}
},
messages: {
name: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
file: {
required: "Please select a file",
minlength: "Your password must be at least 5 characters long"
}
},
submitHandler: function(form) {
if ($('#cfile').val() != "") {
$("#commentForm").validate({
rules: {
file: "required",
file: {
required: true,
minlength: 5
}
},
messages: {
file: {
required: "Please select a file"
}
}
});
$(form).submit();
} else {
alert('file missing.');
}
}
});
Related
Ok so I am using jquery validation plugin to validate my form and it is working good so far my only problem is that i want to check if a username exits while the user is entering data into the form. I have solved the problem already using jquery and plain php. Now i want to do the samething using jquery validation and laravel framework. Here is a sample of my js. As always any help would be appreciated.
var fnameregex = /^[a-z -]+$/i;
var lnameregex = /^[a-z'-]+$/i;
var usernameregex = /^[a-z0-9_'-]+$/i;
var emailregex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var passregex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.{8,})");
var aos = '';
$.validator.addMethod('firstname_regex', function(value,element){
return this.optional(element) || fnameregex.test(value);
},'This name is not valid.')
$.validator.addMethod('lastname_regex', function (value,element) {
return this.optional(element) || lnameregex.test(value);
},'This name is not valid')
$.validator.addMethod('username_regex', function (value,element) {
return this.optional(element) || usernameregex.test(value);
},'This username is not valid')
$.validator.addMethod('password_regex', function (value,element) {
return this.optional(element) || passregex.test(value);
},'Passwords must be eight characters or more contain one uppercase, one numeric number and one lowercase.')
$(function(){
$('#signupform').validate({
rules:{
firstname:{
required:true,
firstname_regex:true,
nowhitespace:true,
minlength:3,
},
lastname:{
required:true,
lastname_regex:true,
nowhitespace:true,
minlength:3,
},
username:{
required:true,
username_regex:true,
nowhitespace:true,
remote:{
url:"checkusers",
type:"post"
}
},
email:{
required:true,
email:true,
nowhitespace:true,
},
password:{
required:true,
password_regex:true,
nowhitespace:true,
},
passconfirm:{
required:true,
password_regex:true,
nowhitespace:true,
equalTo:"#password",
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
$(element).closest('.form-control').css("border-color","#a94442");
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-control').css("border-color","#00b8e6");
// $('#firstname').css("border-color","#00b8e6");
},
messages:{
passconfirm:{
equalTo:"Please ensure your passwords match."
},
firstname:{
minlength:"Please enter a valid name."
},
lastname:{
minlength:"Please enter a valid name."
},
username:{
remote: "This username already exits."
}
}
});
})
i sent a post request to checkusers now i want to tell laravel what to do when it receives such a request if the username is already taken the it should return a response of false therefore the remote validation would fail and give the proper error else return true and it passes the remote validation here is a sample of my route in laravel.
Route::post('checkusers',function(){
$user = users::all()->where('username', Input::get('username'))->first();
if ($user) {
echo "false";
} else {
echo "true";
}
});
i will also include a php script i have which does the work i only need someway of doing the same thing in laravel.
require_once "connect.php";
if(isset($_POST['username'])) {
$username = $_POST['username'];
$result =$conn->query("SELECT username FROM users WHERE username='$username'");
if ($result->num_rows ==0){
echo 'true';
}
else {
echo 'false';
}
}
Update: The email address check for the email field is returning "email address is already in use" upon entering an address regardless if the email address is new or exists in the mySQL database. I would like it to only return the error when an email exists in the email field of the users table in the database.
The current code for the signup page is:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$().ready(function(){
$("#register").validate({
errorElement: 'span',
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.insertAfter($(".term"));
} else {
error.insertAfter(element);
}
},
rules: {
su_email : {
required: true,
email: true,
remote: "/email_check.php"
},
su_password : {
minlength: 6,
required: true
},
su_conpassword : {
equalTo : "#su_password"
},
su_name : {
minlength: 3,
required: true
},
su_phone : {
required: true
},
su_city : {
required: true
},
su_country : {
required: true
},
su_gender : {
required: true
},
su_quest : {
required: true
},
su_ans : {
required: true
},
su_terms : {
required: true
}
},
messages: {
su_email: {
required: "Please enter your email address",
email: "Please enter a valid email address",
remote: jQuery.validator.format("{0} is already in use")
},
su_password: {
required: "Provide a password",
minlength: jQuery.validator.format("Enter at least {0} characters")
},
su_conpassword: {
equalTo: "Repeat your password"
},
su_name: {
required: "Enter your full name",
minlength: jQuery.validator.format("Enter at least {0} characters")
},
su_phone: {
required: "Enter your phone number"
},
su_city: {
required: "Enter your city"
},
su_country: {
required: "Select your country"
},
su_gender: {
required: "Select your gender"
},
su_quest: {
required: "Select a security question"
},
su_ans: {
required: "Select a security answer"
},
su_terms: {
required: "You must agree to terms to join"
}
}
});
$('.condition').click(function () {
if ($(this).is(':checked')) {
$('#termscondition').dialog({
modal: true,
width: 600,
buttons: {
Ok: function() {
$( this ).dialog('close');
}
}
});
} else {
$('#termscondition').dialog('close');
}
});
});
</script>
<?php
include('includes/inc-public.php');
include('includes/classes/class.user.php');
$user = new User();
$email = $_GET['su_email'];
$valid = false;
header('Content-Type: application/json');
if(!is_null($email)){
$is_valid = $user->get_email($email);
if($is_valid){
echo json_encode($is_valid);
}
else{
echo json_encode($valid);
}
};
?>
signup form when a new email address is being entered in the email field
users table of mysql database
From documentation:
The serverside response must be a JSON string that must be "true" for valid elements, and can be "false", undefined, or null for invalid elements, using the default error message. If the serverside response is a string, eg. "That name is already taken, try peter123 instead", this string will be displayed as a custom error message in place of the default.
So you need to change your is_valid to true.
I had a registration form which i added a JQuery validate plugin remote validation in. The purpose of the remote validation is to check if the email/and username entered by the user already exists in my database(i.e is already in use), and will return an error message if it is.The form was working before i added the remote validation.
Now, i am unable to submit the form even when all the data i've entered is correct, and to add insult to injury, no error messages appear when i enter an email that already exists in my database.
My JQuery code:
$(document).ready(function(){
<!--AJAX Call to retrieve type & subtype of industries-->
$("#type").load("getregtype.php");
$('#type').change(function(){
var type=$('#type').val();
$('#subtype').load('getregsubtype.php?type='+type);
});
<!--End of AJAX Call -->
<!--JQuery validation of registration form-->
<!--Set default message for 'equalTo' errors-->
$.extend($.validator.messages, { equalTo: "The values you entered do not match." });
$("#regform").validate({
// Specify the validation rules
rules: {
username: "required",
password: {
required:true,
minlength:6,
},
cpassword: {
required: true,
minlength: 6,
equalTo: "#password"
},
email: {
required: true,
email: true,
remote:"emailcheck.php"
},
cemail: {
required: true,
email: true,
equalTo:"#email"
},
type: {
required: true
},
subtype: {
required: true
},
name: "required"
},
// Specify the validation error messages
messages: {
username: "Please enter a username",
email: {
required:"Please enter an email address",
email:"Please enter a valid email address",
remote:jQuery.format("{0} is already in use")
},
cemail: {
required:"Please enter an email address",
email:"Please reenter your email address",
},
password: {
required: "Please enter a password",
minlength: "Your password must be at least 6 characters long"
},
cpassword: {
required:"Please reenter your password",
minlength: "Your password must be at least 6 characters long"
},
name: "Please enter the name of your business"
},
submitHandler: function(form) {
form.submit();
}
});
});
My PHP page that is called by remote.
<?php
include("cxn.inc");
$query=$cxn->prepare("SELECT * FROM `testdb`.`business` WHERE `Email` = :email");
$query->bindValue(":email",$_GET['email']);
$query->execute();
$count=$query->rowCount();
$mail=$_GET['email'];
print_r($mail);
echo"$count";
if($count>0)
{
echo json_encode('false');
}
else
{
echo json_encode('true');
}
?>
Things tried
print_r($mail) and echo"$count"; both return the correct value.I've also tried
echo json_encode(true);
as well as
return true;
EDIT
Some more things i've tried.
echo true;
I've also tried to pass in the value of the email directly through the url, on the off chance that the value was not being passed to 'emailcheck.php' by doing
email: {
required: true,
email: true,
remote:"emailcheck.php?email=test#test.com"
},
but my form still doesn't work.
I appreciate any insight to my problem.
Thanks!
Your PHP script expects a GET parameter with name email. Just to eliminate the possibilities of errors here, you can set that explicitly in the jQuery code :
rules: {
/* Code skipped ... */
email: {
required: true,
email: true,
type: "get",
remote:"emailcheck.php"
data: {
email: function() {
return $("#email").val();
}
}
},
/* ... */
Make sure that $('#email') really matches your form input.
You can also check the response with Firebug or an equivalent tool (just hit F12 on your browser window and see what comes up), you might want to ensure that the mimetype of the response is application/json.
First of all check js error in your console, if nothing is wrong check also what your script send and what he receive from php
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $("[name='email']").val();
}
}
}
and from the PHP file check-email.php just echo true or false like this:
echo 'false';
or
echo 'true';
not echo false; or echo true;
!!!
I click the button and nothing happens. If I take out the validation code, then clicking the button works and it falls back to the PHP validation that I have implemented. I coded up the jquery validation first and it worked, then I coded up the PHP side. But then the jquery validation stopped working after the PHP side is okay.
Can someone help?
I tried adding
submitHandler: function(form) {
form.submit();
}
like this:
submitHandler: function(form) {
form.submit();
},
rules: {
...
}
But nothing happened.
Here is the relevant code, let me know if anything is unclear, thanks! I've been stuck on this for a while now.
if (isset($_POST['submit']))
{
foreach($_POST as $key=>$value)
{
unset($_SESSION[$key]);
$_SESSION[$key] = $value;
}
$errors = validation($job);
if (count($errors) == 0)
{
sendEmail($job);
sendEmailToApplicant($job);
}
}
$output = "
<script src='http://code.jquery.com/jquery-latest.js'></script>
<script type='text/javascript' src='http://jzaefferer.github.com/jquery-validation/jquery.validate.js'></script>
<script type='text/javascript'>
jQuery.validator.setDefaults({
debug: true,
success: 'valid'
});
jQuery.validator.addMethod('phoneUS', function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, '');
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, 'Please specify a valid phone number');
</script>
<script>
$(document).ready(function(){
$('#applicationForm').validate({
rules: {
firstName: {
required: true,
rangelength: [2, 15]
},
lastName: {
required: true,
rangelength: [2, 15]
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUS: true
},
website: {
url: true
}
}
});
});
</script>
<form id='applicationForm' name='applicationForm' method='post' enctype='multipart/form-data'>
...
<input id='submit' type='submit' name='submit' />
</form>";
really quick to try. not sure if this is the issue since I really didnt look too close, but why is there jQuery. in some actions if you dont have a jquery.noConflict.
try changing those to just $ like this maybe:
<script>
$(document).ready(function(){
$('#applicationForm').validate({
rules: {
firstName: {
required: true,
rangelength: [2, 15]
},
lastName: {
required: true,
rangelength: [2, 15]
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUS: true
},
website: {
url: true
}
}
});
$.validator.setDefaults({
debug: true,
success: 'valid'
});
$.validator.addMethod('phoneUS', function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, '');
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, 'Please specify a valid phone number');
});
Checking whether a post has been made is done using the following code:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
Checking for the existance of the submit button is very unreliable.
I would like to stop the submit button function, when we got any error in HTML form elements (like captcha). We have several functions in our script, let me explain in details.
Check the data validation only captcha security code configured with PHP (through - jquery-1.3.2.js && - validate.js)
Send data through AJAX call (through - ajaxSubmit.js)
now i would like to stop the script, when any of the user filled the wrong value in Captcha text. we just simply disable the submit button and get message ("Form Not Filled Properly...")
UPDATED VALIDATION - please check only with Captcha codes
<script type="text/javascript">
$.validator.addMethod('myEqual', function (value, element) {
if ($('#password-password').val() == $('#password-password-confirm').val()) {
return true;
} else return false;
}, 'Your password does not match.');
$(document).ready(function() {
$('#password-clear').show();
$('#password-password').hide();
$('#password-clear').focus(function() {
$('#password-clear').hide();
$('#password-password').show();
$('#password-password').focus();
});
$('#password-password').blur(function() {
if($('#password-password').val() == '') {
$('#password-clear').show();
$('#password-password').hide();
}
});
$('#password-clear-confirm').show();
$('#password-password-confirm').hide();
$('#password-clear-confirm').focus(function() {
$('#password-clear-confirm').hide();
$('#password-password-confirm').show();
$('#password-password-confirm').focus();
});
$('#password-password-confirm').blur(function() {
if($('#password-password-confirm').val() == '') {
$('#password-clear-confirm').show();
$('#password-password-confirm').hide();
}
});
var validator = $("#signupform").validate({
//ignore: ".ignore",
rules: {
username: {
required: true,
minlength: 5
},
captcha: {
required: true,
remote: "includes/process.php"
},
password: {
required: true,
minlength: 5
},
passwordconfirm: {
required: true,
minlength: 5,
myEqual: true
},
email: {
required: true,
email: true
}
},
messages: {
captcha: "Correct captcha is required. Click the captcha to generate a new one",
username: {
required: "Enter a username",
minlength: jQuery.format("Enter at least {0} characters"),
},
password: {
required: "Provide a password",
rangelength: jQuery.format("Enter at least {0} characters")
},
passwordconfirm: {
required: "Provide a password",
rangelength: jQuery.format("Enter at least {0} characters")
},
email: {
required: "Please enter a valid email address",
minlength: "Please enter a valid email address"
}
},
// the errorPlacement has to take the table layout into account
errorPlacement: function(error, element) {
if ( element.is(":radio") )
error.appendTo( element.parent().next().next() );
else if ( element.is(":checkbox") )
error.appendTo ( element.next() );
else
error.appendTo( element.parent().next() );
},
submitHandler: function() {
alert("submitted!");
},
// specifying a submitHandler prevents the default submit, good for the demo
// set this class to error-labels to indicate valid fields
success: function(label) {
// set as text for IE
label.html("").addClass("checked");
// form.submit();
}
});
});
Please suggest me proper code for our requirement.
With jQuery:
$("#formid").submit(function (){
if(!your condition){
return false;
}
});
Use the onSumbit attribute o fteh form. Assign it the function that you use to check for correct form completion. If the form is correctly filled out then return true; otherwise return false. False will stop the form from being submitted. You could display the required message just before returning false.