Jquery Validation remote method always shows invalid - javascript

I am trying to validate an html function with django and the JavaScript FormValidation plugin. I want validation
to check if the inserted email already exists,
This is my validation remote
email: {
validators: {
notEmpty: {
message: 'email field can not be empty'
},
emailAddress: {
message: 'is not a valid email'
},
remote: {
message: 'email is already in use',
url: '/validate_email/',
type: 'post',
data: {
email: function() {
return $('#email').val();
}
},
},
},
},
The url calls to my view def which is
def validate_email(request):
email = request.GET.get('email', None)
data = not Vendors.objects.filter(email__iexact=email).exists()
if data is True:
data = "true"
else:
data = "false"
return JsonResponse(data, safe=False)
I am getting a correct "true" or "false" JsonResponse, but the message always shows that the email is already in use and keep asking me to correct it.
I tried passing the JsonResponse as true or false without "", also tried passing the JsonResponse as is_taken: true or is_taken: false.

In your Django view, you need to return a JSON response in the following format:
return JsonResponse({"valid": data})
The FormValidation plugin will understand that the email is valid if the response is "valid":true and invalid if the response is "valid": false.

Related

Node.js/Mongoose/lodash - server response: User Validation Failed: path `foo` is required

The error message being received is:
"User validation failed: email: Path email is required., display_name: Path display_name is required."
The error name being sent back is: ValidationError.
The code for the ajax call is:
function submit_new_user(display_name, email, password){
let user_data = new New_User(display_name, email, password);
console.log(user_data);
$.ajax ({
dataType: 'JSON',
data: user_data,
method:'POST',
url: 'http://localhost:3001/user',
success: (res)=>{
console.log(res);
},
error: (xhr, ajaxOptions, thrownError)=>{
console.log(xhr, ajaxOptions, thrownError);
}
});
};
the console.log seen above prints:
New_User {display_name: "test", email: "test#test.com", password: "Passw0rd"}
The server route is:
app.post('/user', (req, res)=>{
let body = _.pick(req.body, ['display_name', 'email', 'password']);
let user = new User(body);
user.save().then(()=>{
return user.generateAuthToken();
}).then((token)=>{
res.header('x-auth', token).send(user);
}).catch((err)=>{
res.status(400).send(err);
});
});
This route works when pinged with Postman. The server supports cors.
The model is as follows:
var UserSchema = new mongoose.Schema({
display_name: {
type: String,
unique: true,
required: true,
validate: {
validator: (val)=>{
return /^[\w\s]+$/.test(val);
},
message: '{VALUE} is not a valid display name. Only
alphanumeric, upper and lower case characters are allowed.'
}
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email.'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access:{
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
I'm still learning node.js. I was guided through the creation of the API, and am trying to build a front end on my own.
The object leaving contains the three value pairs - but the object arriving, before the server changes it, is empty. I'm at loss as to why.
SOLUTION: the problem was in the server-side bodyParser. I had forgotten to include the encoded url method. It was not parsing the JSON as it came in, since previously the API had only been tested using Postman there was no need to use the .urlencoded() method.

ExtJS 6: Validator on a textfield not working properly

I got a signup-form with a textfield for the username.
For this textfield I added a custom validator function to check the availability for the selected username:
xtype: 'textfield',
name: 'username',
msgTarget: 'under',
bind: {
fieldLabel: '{texts.username}'
},
allowBlank: false,
minLength: 3,
checkChangeBuffer: 300,
validator: function (value) {
if (value.length < 3) {
return null;
}
Ext.Ajax.request({
method: 'POST',
url: '/rest/availability',
params: {
name: value
}
}).then(
function (result) {
return Ext.JSON.decode(result.responseText) ? true : 'Username already exists';
},
function (response) {
return 'Server issue.';
}
)
}
This should probably do it. But it doesnt.
I get a broken error, the validator shows always invalid and the message is not displayed:
When I check the response I get the correct value from the server.
What am I missing here?
Thanks in advance.
In order for the validation to pass you need to return true.
validator: function(value) {
if(!valid) {
return 'error message';
}
return true; // successfully passed
}

how to use jquery ajax validation using remote?

I have written a program in jsp to check whether an email address exist in database or not , if it exist it will give me "1" and if it does not exist it will give me default as "0" , which is working perfectly
Now i want to call this url in my jquery and validate my email address , i have written some code in jquery but it is not working , my error message for email is working but for remote is not working. Please need some help
$(document).ready(function () {
$("#user_form").validate({
rules: {
phone: {
required: "true",
minlength: "10"
},
email: {
required: "true",
email: "true",
remote: {
url: 'validate_emailid_succes.jsp',
type: "POST",
data: {
email: function () {
return $("#email").val()
}
}
}
}
},
messages: {
email: {
required: "Please enter your email address",
email: "Please enter a valid email address",
remote: jQuery.validator.format("Email ID is already taken")
},
phone: "Please enter a 10 digit mobile number"
}
});
});
Need some guidance so that i can understand where i am going wrong.
Thank You

Bootstrap Validator - Send all input field values to remote PHP file

I was wondering if there was a way to send all of my input field values to a remote PHP file using Bootstrap Validator.
To explain, I have two input fields in a log in form. I use Bootstrap Validator's remote validation on both of the input fields. Each validation only sends the requested input field's value and there is no access to the other input field via $_POST in the PHP back end.
I know that I can send data to the PHP back end with the data option, but I am unsure as to how the formatting would go if I were to send the values of different input fields in that section.
Here is a coding example.
$(document).ready(function() {
$('#login_form').bootstrapValidator({
fields: {
username: {
message: 'Invalid',
validators: {
remote: {
message: 'Invalid',
url: '/path/to/backend/',
data: {
password: // What do I put here?
}
}
}
},
password: {
message: 'Invalid',
validators: {
remote: {
message: 'Invalid',
url: '/path/to/backend/',
data: {
username: // What do I put here?
}
}
}
}
}
});
});
That coding example is one way to solve my problem and have both input field values submitted to the back end. If anyone has a solution to my problem with this method, or another way that I can go about giving all input field values to the back end, please let me know.
Thank you in advance for any help that you may give.
For sending any input field in your form to the backend, just call a validator function that recalls the values of the input fields in your form and assign them to a parameter with a descriptive name.
This parameter then can be accessed from POST (or from GET i you so configure it) in /path/to/backend.
You can see you code modified below.
I hope it will work for you. It's fully tested code.
Please send feedback.
$(document).ready(function() {
$('#login_form').bootstrapValidator({
fields: {
username: {
message: 'Invalid',
validators: {
remote: {
url: '/path/to/backend/',
data: function(validator) {
return {
password: $('[name="passwordNameAttributeInYourForm"]').val(),
whatever: $('[name="whateverNameAttributeInYourForm"]').val()
};
},
message: 'Invalid'
}
}
},
password: {
message: 'Invalid',
validators: {
remote: {
url: '/path/to/backend/',
data: function(validator) {
return {
username: $('[name="usernameNameAttributeInYourForm"]').val(),
whatever: $('[name="whateverNameAttributeInYourForm"]').val()
};
},
message: 'Invalid'
}
}
}
}
});
});
To send data to backend using bootstrap validator use this code.
$(document).ready(function() {
$('#student_view').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
container: 'tooltip',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
coursename: {
validators: {
notEmpty: {
message: 'Please select course name'
},
remote: {
url: 'abc.php', //path to backend
data: function(validator) {
return {
course: $('#course').val(), //sending dynamic data value
password: $('#password').val()
};
},
message: 'Invalid'
}
}
},
}
})
.on('success.form.bv', function(e) {
$('#student_view').data('bootstrapValidator').resetForm();
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
backend must return output in the following format
{ "valid": true } or { "valid": false }

jQuery .Validate() Remote sucess function and message

I need to validate an email field using the jQuery.Validate() plugin it has a "Remote" method which we have to post to a server and server needs to return true or false, Instead of using the traditional way(adding a function on the server to return true or false), I need to get json response from the server and on success run a function to decide where to return true or false...
Here is what the response from the server looks like (I'm using the Yii ajax form validation)
{
"zipcode":[
"Zipcode cannot be blank."
],
"email":[
"Email is already registered"
],
}
If email is listed on the array that means the validation had errors So I create a Remote validation rule like follows:
'email': {
required: true,
email: true,
remote:{
type:"POST",
url:url,
dataType:'json',
data:{'email':function(){
$('#email').val();
},ajax:'validate'},
success:function(resp){
$.each(resp,function(index,value){
if(index == "email")
return false;
});
}
}
},
But does not work, also I did not found anywhere where I can add the error message for remote validation, I would like to pass the array email value as the message...
You need to replace your success function with below function :
dataFilter: function (data) {
return 'false'; //Email not exist
return 'true'; //Email already exist
}
Please pass true/false value as a string.
For Display Message :
remote:{......},
messages:{email:'Please enter valid email', remote : "{0} is already exist"}
I think this will be help.

Categories

Resources