Current I have the following custom rules to validate fields of my form.
Rules
$scope.validator = $("#frmPreregistration").kendoValidator({
rules: {
varifySsn: function (input) {
var ret = true;
if (input.is("[name=last4Ssn]") && $scope.Last4DigitsSsn != undefined ) {
ret = $scope.validateSsnLast4Digit();
}
return ret;
},
varifyDob: function (input) {
var ret = true;
if (input.is("[name=dob]") && $scope.DateOfBirth != undefined ) {
ret = $scope.validateDateOfBirth();
}
return ret;
},
varifyZipCode: function (input) {
var ret = true;
if (input.is("[name=zipCode]") && $scope.ZipCode != undefined ) {
ret = $scope.validateZipCode();
};
return ret;
}
},
messages: {
varifySsn: $scope.resources.SsnLast4DigitDoesNotMatch,
varifyDob: $scope.resources.DobNotMatchWithSelectedUserType,
varifyZipCode: $scope.resources.ZipCodeNotMatchWithSelectedUserType,
}
}).data("kendoValidator");
I am validating the form whenever user enters a value in any of the field in the form by $scope.validator.validate()
This is resulting in firing the rules for all the fields even before the user enters any value into it.
Question
Is there any possibility that I can run a particular validation rule at a time or run validation for a particular field?
You can use validateInput for specific element.
Example:
$scope.validator.validateInput($("input[name=dob]"));
to hide invalid message you can use hideMessages function
$scope.validator.hideMessages();
Related
I want the form to post the credentials via a get request but have difficulties making it work together with the onsubmit parameter which is used to validate the data entered. This is my form code:
<form onsubmit="return formValidation()" action="show_get.php" method="get" name="registration">
This is the code I used for validation
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
{
if (allLetter(name)) {
if (ValidateEmail(uemail)) {
if (checkDate()) {
}
}
}
return false;
}
}
function allLetter(name) {
var letters = /^[A-Za-z]+$/;
if (name.value.match(letters)) {
return true;
}
else {
alert('Name must have alphabet characters only');
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
}
}
If you attach an onsubmit event handler and it returns false, the form will not be submitted. In your case, that always happens, even if the input is valid.
You check allLetter(), then ValidateEmail() and checkDate(), but you don't return true when they're all valid. Your code continues and it reaches return false;. The submit event handler returns the result of that validation function (which is false), so it returns false too. This tells the form to not submit.
Change your validation function to this:
function formValidation() {
var name = document.registration.name;
var uemail = document.registration.email;
if (allLetter(name) && ValidateEmail(uemail) && checkDate()) {
return true;
} else {
return false;
}
}
If all three checks return true, the validation function will return true as well and the form will be submitted.
Note: You had one unnecessary pair of brackets ({}), I removed them. I also improved readability by combining all the nested if statements into one.
Edit: Also, your checkDate() doesn't return true and false accordingly. It returns undefined by default, which is a falsy value. This means that it won't pass the validation function's && check and the form won't get submitted. Change checkDate() to this:
function checkDate() {
var selectedText = document.getElementById('datepicker').value;
var selectedDate = new Date(selectedText);
var now = new Date();
if (selectedDate < now) {
alert("Date must be in the future");
return false;
} else {
return true;
}
}
Edit 2: You also incorrectly get the values of your input elements. When you do this:
var name = document.registration.name;
var uemail = document.registration.email;
You get the HTML element with name attribute name and HTML element with name attribute email. You should get the elements' values:
var name = document.registration.name.value;
var uemail = document.registration.email.value;
It's best to edit your answer and add the full HTML and JavaScript. There might be more problems.
I am getting an error while setting global variable flag inside function.
Global variable declaration
var flag = false;
Function to validate textbox
//To validate Product Name field
function Name() {
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
flag = false;
}
else {
$('#productNameError').text('');
flag = true;
}
}
Function to validate quantity
//To validate Product Quantity Field
function Quantity() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
flag = true;
}
else {
$('#productQtyError').text('Enter Quantity of the Product');
flag = false;
}
}
else {
$('#productQtyError').text('Quantity is required');
flag = false;
}
}
//Validation Summary
function validate() {
if (flag == true) {
$('#validationSummary').text('');
return true;
}
else {
$('#validationSummary').text('Please fill out required fields.');
return false;
}
}
I am calling first two functions on onfocusout event of textbox and calling validate() function on button click. The problem which I am facing is: inside the Quantity() flag is not getting set to false. Although the field remains blank,record gets inserted.
if you are getting flag=true in validate() then you may be calling Quantity() first ,it will set flag false then Name() which will set flag to true so It bypassed validate() function.
This is not the correct way, you are trying to achive validation. Consider scenario, when user have entered the correct value in first filed, flag will be set to true with the fact that second field is empty amd form will be submitted and hold true vice versa.
If want to achive by this way, keep as many flag variables as the number of fields amd chech all those variable inside validate.
Or, use '.each' to iterate each element and validate it and keep appending validation mesages to dom object.
Thanks
Don't use Global Variables
You're going to have a bad time if you use global variables, you can use the revealing module pattern to encapsulate some of the messiness
Would suggest something like this :
var app = app || {};
app.product = app.product || {};
app.product.validate = app.product.validate || {};
app.product.validate.isValid = false;
app.product.validate.name = function(){
var pName = document.getElementById('addPName').value;
if (pName == "") {
$('#productNameError').text('Product Name is required');
app.product.validation.flag = false;
} else {
$('#productNameError').text('');
app.product.validation.flag = true;
}
}
app.product.validate.quantity = function() {
var pQty = document.getElementById('addPQty').value;
if (pQty != "") {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(pQty)) {
$('#productQtyError').text('');
app.product.validate.flag = true;
} else {
$('#productQtyError').text('Enter Quantity of the Product');
app.product.validate.flag = false;
}
} else {
$('#productQtyError').text('Quantity is required');
app.product.validate.flag = false;
}
}
console.log is Your Friend
Try putting a console.log inside some of those methods, what I am guessing your issue is is that something is being called out of the order you expect and setting the flag to a value you aren't expecting.
Can do console.log statement like this console.log if you open up your developer console should show you the output from the console
I have a simple form I'm making client side validation for.
To validate, none of the fields should be left blank.
This is how I go at it:
function validateForm() {
$('.form-field').each(function() {
if ( $(this).val() === '' ) {
return false
}
else {
return true;
}
});
}
For some reason, my function always returns false, even though all fields are filled.
You cannot return false from within the anonymous function. In addition, if it did work, you would return false if your first field was empty, true if not, and completely ignore the rest of your fields. There may be a more elegant solution but you can do something like this:
function validateForm() {
var isValid = true;
$('.form-field').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
return isValid;
}
Another recommendation: this requires you to decorate all of your form fields with that formfield class. You may be interested in filtering using a different selector, e.g. $('form.validated-form input[type="text"]')
EDIT Ah, I got beat to the punch, but my explanation is still valid and hopefully helpful.
You were returning from the inner function not from the validate method
Try
function validateForm() {
var valid = true;
$('.form-field').each(function () {
if ($(this).val() === '') {
valid = false;
return false;
}
});
return valid
}
function validateForm() {
var invalid= 0;
$('.form-field').each(function () {
if ($(this).val() == '') {
invalid++;
}
});
if(invalid>0)
return false;
else
return true;
}
Here is a similar approach:
function validateForm() {
var valid = true;
$('.form-field').each(function() {
valid &= !!$(this).val();
});
return valid;
}
!! just converts input value to bool
I have a function that simply validates forms (for old browsers). The function works just fine except that I have to pass the parameters every time I call this function, where in fact I already specified the default parameters in 'config'.
So by logic, If I called the function as: validateMe(); it should run as validateMe({requiredClass: '.required', verifiedClass: 'invalid'});
but unfortunately calling the function without parameters doesn't work correctly ( in my case the form triggers the submission event) (it doesn't reach return false).
so what is missing in the code to run the function with the default settings??
function validateMe(vform, settings) {
var vform, //form name or id
config = {
'requiredClass': '.required',
'verifiedClass': 'invalid'
};
if (settings) {
$.extend(config, settings);
}
$(vform).on('submit', function(){
var inputs = $(this).find(config.requiredClass),
required = [];
for (i=0; i < inputs.length; i++) {
if (inputs[i] != null) {
if ($(inputs[i]).val().replace(/^\s+|\s+$/g, '') == '') {
required.push($(inputs[i]).index());
}
}
}
if (required.length > 0) {
$(this).find('input').removeClass(config.verifiedClass);
for(n=0;n<required.length;n++) {
$(inputs[n]).addClass(config.verifiedClass);
}
return false;
}
});
}
Any help?
Thanks.
function validateMe(vform, settings) {
this.vform = vform || 'default',
this.setting = 'whatever',
this.private = ''
}
var newInstance = new validateMe();
now you have an instance of it, so you can define it as you go.
I am using VS 2010 with MVC 3 and unobtrusive validation. I am attempting to create a custom range validator to includes warnings where input values are acceptable but unexpected. (I have working functionality to submit the values with wanings by using the ignore option of the form validator)
The unobtrusive component is:
// The adapter to support ASP.NET MVC unobtrusive validation //
$.validator.unobtrusive.adapters.add('rangewithwarning', ['min', 'max', 'wmin', 'wmax', 'warning'],
function (options) {
options.rules['rangewithwarning'] = {
min: options.params.min,
max: options.params.max,
wmin: options.params.wmin,
wmax: options.params.wmax,
warning: options.params.warning
};
options.messages['rangewithwarning'] = options.message;
});
I have Googled extensively on dynamic error messages which seem to come down to three methods but none of these allow me to display the optional error message. These are:
Returning the error message
// The validator function
$.validator.addMethod('rangewithwarning', function (value, element, params) {
if (!value) {
return true; // not testing 'is required' here!
}
var intValue = parseInt(value);
// set logic here
if (intValue >= params.wmin && intValue <= params.wmax) {
// OK within both actual and range warning
return true;
}
if (params.min <= intValue && intValue <= params.max) {
// outside warning but within allowed range - show warning
return params.warning;
}
return $.validator.messages.rangewithwarning;
});
Use showErrors
// The validator function
$.validator.addMethod('rangewithwarning', function (value, element, params) {
if (!value) {
return true; // not testing 'is required' here!
}
var validator = this;
var intValue = parseInt(value);
// set logic here
if (intValue >= params.wmin && intValue <= params.wmax) {
// OK within both actual and range warning
return true;
}
if (params.min <= intValue && intValue <= params.max) {
// outside warning but within allowed range - show warning
var errors = new Object();
errors[element.name] = params.warning;
validator.showErrors(errors);
}
return false;
});
Return an additional parameter from a messager function
None of these worked although when stepping through the second one the optional message was shown briefly then overwritten.
I'm clearly missing something obvious but cannot see what it is.
Thanks in advance.
Found a solution which was to use the standard range attribute and then follow it with my new warn only attribute
(function ($) {
// The validator function
$.validator.addMethod('rangewarning', function (value, element, params) {
var localElement = $(element);
localElement.siblings("span").removeClass("warningOnlyDataOK")
localElement.removeClass("warningOnlyDataOK")
if (!value) {
return true; // not testing 'is required' here!
}
var intValue = parseInt(value);
// set logic here
if (intValue >= params.wmin && intValue <= params.wmax) {
// OK within both actual and range warning
return true;
}
// set display and ignore class items here etc
localElement.siblings("span").addClass("warningOnlyDataOK")
localElement.addClass("warningOnlyDataOK")
return false;
});
// The adapter to support ASP.NET MVC unobtrusive validation //
$.validator.unobtrusive.adapters.add('rangewarning', ['wmin', 'wmax'],
function (options) {
options.rules['rangewarning'] = {
wmin: options.params.wmin,
wmax: options.params.wmax
};
options.messages['rangewarning'] = options.message;
});
} (jQuery));
Where the class warningOnlyDataOK is used to both display a different style error message and to ignore that validation on save.