rules: {
email : {
required : true,
email : true,
remote: {
url: SITE_URL + 'index.php?sign_up/emailValidate',
type: "post",
data: {
email: function() {
return $("#email").val();
}
}
}
}
},
message:{
email: {
required : "Email cant be empty.",
email : "Please enter a valid email",
remote : "This email already exists."
}
}
You have a typo in your code. You should use 'messages' instead of 'message'.
messages:{
email: {
required : "Email cant be empty.",
email : "Please enter a valid email",
remote : "This email already exists."
}
Related
Lang
"Min_UserName" => "Min :chars chars for username",
JQuery
$("form#registerForm").validate({
rules: {
UserName: {
required: true,
minlength: 6
}
},
messages: {
UserName: {
required: "{!! trans('Register.Required_UserName') !!}",
minlength: "{!! trans('Register.Min_UserName',
['chars' => '\App\UserMinValue::Min_UserName']) !!}"
}
}
});
Class
namespace App\Architecture\MinMaxValues;
class UserMinValue {
const Min_UserName = 6;
}
Current Output
minlength: "Min App\UserMinValue::Min_UserName chars for username",
Expected Output
minlength: "Min 6 chars for username",
Am I missing anything?
You have a quote around the Class path so string path is sent out and not the value you need, change:
['chars' => '\App\UserMinValue::Min_UserName']
To:
['chars' => \App\UserMinValue::Min_UserName]
This is driving me nuts. Doing a simple check for whether or not an email address exists in my database via php using ajax in an addMethod rule to my validator. I've confirmed the php file is outputting "true" or "false" properly upon finding the email or not but the rule always returns true even though the response is correct and the value is false.
This is the rule:
$.validator.addMethod("isExisting", function() {
var checkemail=$("#email").val();
console.log('Email: '+checkemail); // shows email populated correctly
if(checkemail){
$.ajax({
type: 'post',
url: 'checkemail.php',
data: {email:checkemail,},
success: function(response){
console.log(response); // properly returns text "false" when email not found
var exists = (response=="false") ? false : true;
console.log('exists = '+exists); // is properly false
return exists; // returns false
}
});
}
});
And in the validator -
(the "isExisting" error message always pops up regardless of whether the email really exists or not):
$("#signupform").validate({
errorLabelContainer: "#errors",
errorPlacement: function (error, element) {
error.insertAfter(element);
$(element).addClass(errorClass).removeClass(validClass);
},
rules: {
fullname: {
required: true,
minlength: 2
},
email: {
required: true,
email: true,
isExisting: true
},
areacode: {
required: true,
digits: true,
minlength: 3
},
prefix: {
required: true,
digits: true,
minlength: 3
},
num: {
required: true,
digits: true,
minlength: 4
},
address: {
required: true,
},
city: {
required: true,
},
noRobot: {
isCaptcha: true,
}
},
messages: {
fullname: {
required: "Please enter your full name.<br />",
minlength: "Please enter your First and Last name.<br />"
},
email: {
required: "Please enter your email address.<br />",
email: "Please enter a valid email address.<br />",
isExisting: "There is already an account with that email address.<br />"
},
areacode: {
required: "Please enter your areacode.<br />",
minlength: "Your areacode should be 3 digits. »XXX« XXX-XXXX<br />"
},
prefix: {
required: "Please enter your phone number prefix.<br />",
minlength: "Your phone number Prefix should be 3 digits. XXX »XXX«-XXXX<br />"
},
num: {
required: "Please enter your phone number suffix.<br />",
minlength: "Your phone number Suffix should be 4 digits. XXX XXX-»XXXX«<br />"
},
address: {
required: "Please enter your Street Address for pick-up service.<br />"
},
city: {
required: "Please enter your town or city.<br />"
},
noRobot: {
isCaptcha: "Please verify that your are not a spam Robot.<br />"
}
}
});
I would think the "isExisting: true" would only validate true if the true value was returned from the response. (scratches head in frustration...)
checkemail.php:
else{
$result = mysqli_query($connect, "SELECT * FROM `customer_info` WHERE `email`='$email' LIMIT 1");
$num = mysqli_num_rows($result);
if($num > 0){
echo "true";
}
else {
echo "false";
}
}
mysqli_close($connect);
My understanding is that the validator methods should return true when the response is valid. In your case, the valid response is to not have a matching email, so you want to return true if the AJAX call returns false.
It would probably be less confusing to make this method isUnused rather than isExisting to avoid the boolean confusion, but you would need to change checkemail.php as well.
Edit: Disregard my answer above, I clearly misunderstood the problem.
I think the real issue is to do with asynchronous calls. Try setting async: false in your ajax call.
I'm trying to make a form validated before submit. For this, I defined a create method within the View which is responsible to call collection.create() method to create the model.
Here is a sample code:
app.ContactCreateView = Backbone.View.extend({
template: _.template($('#tpl-create-contact').html()),
initialize: function () {
this.router = new app.ContactsRouter();
this.contacts = new app.ContactsCollection();
},
events: {
'click #btn-create' : 'create',
'click #btn-cancel' : 'cancel',
},
render: function() {
this.$el.html(this.template());
return this;
},
getAttributes: function () {
console.log('getAttributes()');
var attr = {
name: $('#input-name').val().trim(),
category: $('#input-category').val().trim(),
phone: $('#input-phone').val().trim(),
email: $('#input-email').val().trim(),
};
console.log('attr : ' + JSON.stringify(attr))
return attr;
},
create: function () {
console.log('create()');
// Create the Model
this.contacts.create(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
//this.hideErrors();
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
//this.showErrors(errors);
}
});
},
The 'success' callback is well called but I don't manage to get the 'error' callback called once the model.validate() method is failing.
Here is the model with the validate method :
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
// Default attributes for the Contact
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
And the collection:
app.ContactsCollection = Backbone.Collection.extend({
model: app.ContactModel,
url: '/user',
//localStorage: new Backbone.LocalStorage('contacts-backbone'),
getById: function (iId) {
return this.where({id: iId});
},
getByName: function (iName) {
return this.where({name: iName});
}
});
I really don't understand what I'm doing wrong... If somebody can help me :-(
Regards,
when the validation is failed error callback is not called , it trigger an "invalid" event on model, and set the validationError property on the model.
method 1(listening on model):
app.ContactModel = Backbone.Model.extend({
urlRoot: '/user',
//your error catched here
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
defaults: {
name: null,
phone: null,
email: null,
category: null,
photo: "/images/placeholder.png"
},
validate: function(attrs) {
console.log('validate() : ' + JSON.stringify(attrs));
var errors = [];
if (!attrs.name) {
errors.push({name: 'name', message: 'Please fill name field.'});
}
if (!attrs.category) {
errors.push({name: 'category', message: 'Please fill category field.'});
}
console.log('errors : ' + JSON.stringify(errors));
return errors.length > 0 ? errors : false;
}
});
method 2 (check whether validationError property is set in your view):
create: function () {
console.log('create()');
// Create the Model
this.contactModel.save(this.getAttributes(), {
wait : true,
success: function () {
console.log('success');
this.contacts.add(this.contactModel);
var router = new app.ContactsRouter();
router.navigate('contacts', true);
},
error: function () {
console.log('error(s)')
}
});
//your error catched here
if (this.contactModel.validationError) {
alert(this.contactModel.validationError)
}
},
So I played around with this for a while in an app I'm currently working on and found it kind of irritating and never really got it to work.
Instead I went the jQuery validation route and found it very helpful for doing validations. I highly recommend checking it out! It has a lot of built in validations you can just use and you can also override the error messages that display (also built in).
Example - I wanted a number only text field (excuse the coffeescript) :).
jQuery.validator.setDefaults(
debug: true,
success: "valid")
if #model.get('number_only')
$('#number_only').validate({
debug: true,
rules: {
"number[entry]": {
required: true,
range: [#model.get('min_number'), #model.get('max_number')],
number: true
}
},
messages: {
"number[entry]": {
required: "This field is required. Please enter a numeric value.",
min: jQuery.validator.format("Please enter a value greater than or equal to {0}."),
max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
number: "Please enter a numeric value"
range: jQuery.validator.format("Please enter a value between {0} and {1}.")
}
}
})
If that doesn't really get what you want (seemed like you maybe are more interested in displaying the errors your server sends back whereas this route would more be validating the content before saving your model) let me know and I can see if I can figure out your problem.
I am trying to implement ajax in laravel framework, where I am trying to check for the availability for the username, I was able to implement the same via core php but not able to get through laravel 4.
1) You have to define a method in your controller (i.e UserController)
public function postEmail()
{
$userCount = User::where('email', '=', Input::get('email'))->count();
if ($userCount == 0)
{
return "true";
} else {
return "false";
}
}
2) In your registration form you have to do jQuery validation like this to make a remote call on Controller method
$(document).ready(function() {
$('#registration-form').validate({
rules: {
email: {
required: true,
email: true,
remote: {
type: "POST",
url: '/user/email'
}
}
},
messages: {
email: {
remote: "The email has already been taken!"
}
},
success: function(date) {
console.log(data);
}
});
What I am trying to do is to show a validation message when username or email exists while trying to register. I have used json_encode which has a message and status. What is happening is that when I type an username and email that exists it doesn't do anything neither shows a message or register.
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST["password"] !== $_POST["confirmation"])
{
echo json_encode(array('msg'=>"password and confirmation aren't equal.", 'url'=>"", 'status'=>false));
}
else if(($data['username']=== $_POST['username'] )|| ($data['email'] === $_POST['email'] ))
{
echo json_encode(array('msg'=>"Username or email exists.", 'url'=>"", 'status'=>false));
}
else
{
$result = query("INSERT INTO users (username, hash, email) VALUES (?,?,?)", $_POST["username"], crypt($_POST["password"]), $_POST["email"]);
$rows = query("SELECT LAST_INSERT_ID() AS id");
$id = $rows[0]["id"];
$_SESSION["id"] = $id;
echo json_encode(array('msg'=>"Success.", 'url'=>"/kinema/html/index.php", 'status'=>true));
}
}
scripts.js
$('#register_form').on('submit', function(e) {
e.preventDefault();
var name = $('#register_form input[name=username]').val();
var email = $('#register_form input[name=email]').val();
$.ajax({
url: "register.php",
type: "POST",
data: {
username: name,
email: email
},
dataType: 'json',
success: function(response) {
if(response.status){
console.log(response);
window.location = response.url;
}
else
{
$('#invalid_register').html(response.msg);
}
}
});
});
You are not posting a password or confirmation value this wil throw an undefined index error.
And for what I can tell the $data array does not exist or the code you posted is incomplete.