I am having an aspx form and in that i need to do validations using jquery or javascript.
I just want to give a message near to the textbox if a user enter a value which is not valid in that textbox.Inorder to display the message in a popup [not alert('message')]
How can I find the position of the textbox in which user enters the invalid data or how can i display a message near the textbox using javascript or jquery ?
I need the validation occur in blur.So it is easy for user to know whether he entered a valid data immediately after giving the input.
Thanks in advance.I am not interested to use asp.net ajax validation and its callout extender.
I just want to implement a functionality which is similar to validation callout extender does.
When you bind the blur event to the textbox, you know which textbox it is. Just use your callback javascript to insert the error near by.
If you're doing jquery, it might look something like:
$('.my_textboxes').blur(function() {
var textbox = $(this);
//ajax validation call
$.post('/whereever', {}, function(response) {
//ajax callback
if (response == 'error') {
textbox.next().html(error); //something like this to insert the error into the next element after the texrbox, eg, a span to hold the error
}
});`
You can use the jQuery (ASP.NET) Validator Callout Plugin
You can use the jQuery validation plugin
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.pack.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
Which has options to specify the message beside the control or to specify all the message at one place.
The demos are available at
http://docs.jquery.com/Plugins/validation
Exactly how you do this depends on the layout of your form, but in general you probably would do something like this: if the validation returns an error for a text field, check to see if an "error box" already exists for that field. If so, then just update its contents with the new error message; if not, then add the error element.
One way to do that would be to use a <span> tag with a particular class (for layout purposes), and an "id" value made from the input field's "name" or "id":
$.fn.setValidationResult = function(errorMessage) {
return this.each(function() {
var errId = 'errMsg_' + this.name, errMsg = $('#' + errId);
if (!errMsg.length) {
$(this).after($('<span></span>', { class: 'validation-error', id: errId }));
errMsg = $('#' + errId);
}
if (errorMessage)
errMsg.html(errorMessage).show();
else
errMsg.html('').hide();
});
});
Then you can just use $(yourInput).setValidationResult(whatever); with "whatever" being empty when validation passes.
Related
I have a form master detail for tabular input and with enabledAjaxValidation=true
So far so good, the form validates all the rules and shows the error messages when submitting or changing any value of any control (onchange event). The problem comes when I add controls to the form using ajax, the latter do not behave like the original ones, they do not show the error messages.
The same when do submit with button
I think that
You need to add the newly created/added field to the validation manually for any dynamically created inputs using the yiiActiveForm.add() function.
You havent added the code you are currently using when you click on the button and add a new input to the form via ajax. So what you need to do is when you receive the response and append the input to the form just add the new input using the following code.
Note: Change the form and field attributes accordingly
$('#form-id').yiiActiveForm('add', {
id: 'input-id',
name: 'input-name',
container: '.field-input',
input: '#input-id',
error: '.help-block',
validate: function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {message: "Validation Message Here"});
}
});
Read more about the activeform valiadation js
Update
If you dont wish to add the validation function manually for every input and you have tabular inputs you can access any of the already created similar field and bind the validation function from it.
For instance in the above example if the the name field is tabular and belongs to the model Contact and you already have a name field populated in the form #contact-0-name you can use the yiActiveForm.find() function to access the attributes of that field and assign the existing validation. see an example below
var fieldAttributes = $("#form-id").yiiActiveForm("find", 'contact-0-name');
$('#form-id').yiiActiveForm('add', {
id: 'contact-1-name',
name: '[1][name]',
container: '.field-name',
input: '#contact-1-name',
error: '.help-block',
validate: fieldAttributes.validate
});
use somthing like below code
error: function(jqXHR,textStatus,errorThrown) {
stopLoader('.modal-content');
$('.csv_errors').show();
if(jqXHR.status==422){
var responseText = $.parseJSON(jqXHR.responseText);
$.each(responseText.errors,function(key,value){
$('.csv_error ul').append('<li>'+value+'</li>');
});
}else{
var responseText = $.parseJSON(jqXHR.responseText);
$('.csv_error ul').append('<li>'+responseText.message+'</li>');
}
}
I have a problem, I validate my form with js plugin Parsley , and on pages where Parsely plugin is initiated the form input type="file" is not working, not clickable" , is see the button animates when clicked but no pop up for the file-system to pick file for upload, and the input is not validated by parserly , inputs on ALL the page where there is Parsly do not work, when I comment out the Parsley instantiation the file input works as expected, here is how I init the plugin:
app.Manage.BasicInfoForm.parsley(app.Manage.validatorConfig).validate();
before this line is executed the inputs work fine also if I have custom validators declared it will prevent file input from working as well like:
window.Parsley.addValidator('reservednamescheck',
function (value, requirement) {
var noAllow = app.websiteManage.noAllowWebsiteNames;
var forbbidenName = '';
for (var i = noAllow.length - 1; i >= 0; i--) {
if (value === noAllow[i]) {
forbbidenName = noAllow[i];
return false;
}
}
return true;
}, 32)
.addMessage('en', 'reservednamescheck', 'Sorry but this name is reserved');
so this will prevent file input from working as well, again, even if file input is standalone anywhere on the page it does not work when Parsley is present, Please help, Thank You
my bad, the problem was not with the plugin but with an jquery event , this code was causing the problem:
$(document).on('click input ', app.websiteManage.websiteNameInput , function(event) {
event.preventDefault();
// detects if inputed website name accordingly changes the title
app.websiteManage.websiteNameBind.html(app.websiteManage.websiteNameInput.val());
});
so I was listening to click and preventing the default behavior , that is why my input file was not working, thank You for everyone who tried to help ;)
Check your version number. The API has changed, and in the 2.0+ version, the 3rd parameter is the parsley instance.
So you would add the message inside your function, something like:
window.Parsley.addValidator('myvalidator', {
requirementType: 'string',
validateMultiple: function(value, dataProp, instance) {
.
.
.
instance.reset(); // clear previous error
instance.addError('en', {message: 'my message here'});
return false;
},
messages: {
en: '...'
}
})
I have two select boxes and i dont want that the user choose the same value in both.
I've tried some solution proposed on stack, but the materialized select is different from "normal select" as contains the options in list item elements.
However, i came up with a solution, which is all but elegant, i know..im a novice with these things.
But its not working as i intended.
I want to create an additional method for jquery validation plugin, in the example on fiddle i've inserted an additional field to show the error placement.
I think is pretty simple, but i just can't figure out how to do it...
$.validator.addMethod("checksameval", function(value, element) {
return $('#pref1').val() == $('#pref2').val()
}, "Pref1 and Pref2 cant have same value!");
https://jsfiddle.net/L24otmaa/5/
edited with custom method (still not working..)
The problem with your solution is that the form will still be valid and therefore it will be possible to send it anyway.
You have to add a custom validation. The plug-in offers a callback where you can check whatever you want before you finally submit it.
This can be done by adding your validation to a custom submit handler
var isSameValue = function() {
var val1 = $('#pref1').val();
var val2 = $('#pref2').val();
if (val1 == val2) {
$customErrorDiv.text('error you cant select same value twice!!');
return true;
}
$customErrorDiv.text('');
return false;
}
// check also on runtime
$('.course').change( function() {
isSameValue();
});
$("#application").validate({
// check before submitting
submitHandler: function(form) {
if (isSameValue()) {
return;
}
// submit the form manually
form.submit();
}
});
Fiddle: https://jsfiddle.net/7uhkddrx/
Documentation: https://jqueryvalidation.org/validate/
Of course you would have to style this message according to your needs.
EDIT: By the way: currently your select boxes are not set to be required.
EDIT2: added checking on runtime
I am using Vue JS with Vue Validator.
As per the project requirement I need some server-side validations to check duplicate entries.
For this, I put a watcher on email_id field, on change of the same an ajax request returns whether the provided email address is duplicate or not (true or false).
If false then I need to set error dynamically for the same.
Everything works fine but the problem is, the error message gets disappear automatically on blur of any field on the form.
You may check my codes here : https://jsfiddle.net/m670da45/23/
Please let me know how to prevent hiding error message i.e. set dynamically?
P.S. For easy understanding, instead of using ajax request, I have set an email address "xyz#xyz.com". Insert given email address in Email field and navigate to Alternate email field, again navigating to Email field will hide the error message.
You could create a custom validator which returns a Promise like this:
Vue.validator('exist', function (val, arg) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (val === 'xyz#xyz.com') {
reject()
} else {
resolve()
}
}, 1000)
})
})
https://jsfiddle.net/pespantelis/m670da45/24/
For more details about the async validation, you could check the related section on Docs: http://vuejs.github.io/vue-validator/en/async.html
I'm working on my first HTML form that performs an AJAX HTTP POST using jQuery. When a user makes a change to an input text field and tabs out of the field it triggers the AJAX script which in turn calls a PHP script which performs a database update.
I've got this working successfully for my first input field - I would now like to extend this to a 2nd, 3rd etc input fields but want to try and avoid having multiple scripts that perform very similar functions. I'm new to jQuery and AJAX so learning the syntax as I go.
Here's my input fields:
Manager
Phone
Here's my Javascript that is working on the storeManager input field:
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){
var storeManager = $("#storeManager").val();
$.post('editProject.php', { storeManager: storeManager, id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
$("#managerRow").addClass("success");
}).fail(function () {
// no data available in this context
$("#managerRow").addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
});
</script>
I essentially need to branch and pass an additional POST parameter to the editProject.php script so it knows which database field to update, and then conditionally add a class to the appropriate row.
Everything I've tried breaks the script when I try and get it to branch or pass a parameter based on the input field that is being edited. I haven't been able to find any examples that show the correct syntax to have the one script that is called by different input fields - I'm presuming this is possible instead of having multiple versions of the same script acting on different fields.
This works for multiple fields. Just call the same function from different input fields. I just broke your code into two parts.
1. onChange function of each individual field, and
2. function call by passing the field parameters.
<script type="text/javascript">
$(document).ready(function() {
$("#storeManager").change(function(){ yourFunction(this) }):
$("#worker").change(function(){ yourFunction(this) }):
$("#someX").change(function(){ yourFunction(this) }):
yourFunction(field)
{
var value = $(field).val();
var inputId=field.id;
$.post('editProject.php', { inputValue: value, id: inputId }, function(data) {
$('#'+inputId+'Row').addClass("success"); // (this looks like: *#storeManagerRow* ) you can change your Row id's accordingly to make your work easier. Eg: for **#storeManager** make this id as **storeManagerRow**
}).fail(function () {
// no data available in this context
$('#'+inputId+'Row').addClass("danger");
$("#ajaxAlert").addClass("alert alert-danger");
});
});
</script>
You just try to post a value. for example type. Which should contain some value for identify the ajax call.
If it is for login, then add type = 'login'. Then check the value of $_POST['type'] and write php according to it
sample.php
if(isset($_POST['type']))
{
if($_POST['type'] == 'login')
{
//your code goes here
}
}
you can use this kind of code :
$("#storeManager, #Manager, #Phone").change(function(){
You could do something like this using :input or a class that they all have
$(":input").on("change", function(){
var text = $(this).val();
var idOfInput = $(this).attr("id");
//your post to php function using the above variables
});
From this you could post the id of the input to your php script using the idOfInput variable which you could then on the php side use a case switch to do a different query depending on which id is sent to the php
Here is a jsfiddle showing how it works