jQuery plugin for inline form validation - javascript

I m using jQuery plugin for inline form validation in my .NET web application.
With following:
jquery.validationEngine.js
jquery.validationEngine-en.js
jquery-1.6.min.js
validationEngine.jquery.css
template.css
Now i have two html <select> , one is for minimum value and second is for maximum value. Values should be check onchange.
How to use custom functions to Validate minimum and maximum values.

Untested but according to the reference of the jQuery plugin, you can work with custom functions to validate a field value:
HTML:
<input class="validate[required,funcCall[checkMinMax]]" type="text" ...
JavaScript:
function checkMinMax(field, rules, i, options) {
var minVal = parseInt($("#sel_min").val(), 10),
maxVal = parseInt($("#sel_max").val(), 10);
if(!isNaN(minVal) && !isNaN(maxVal)) {
if (minVal > maxVal) {
return 'YOUR MESSAGE TEXT HERE';
} else if (maxVal < minVal) {
/* OR use the options with */
return options.allrules.validate2fields.alertText;
}
}
}
It's a long time since I saw the usage of another jQuery validation plugin than jQuery validate, comparing both I suggest you should look into this, because it became more a less the 'standard' way to handle form validation with jQuery, it's well documented and you'll find most of the problems already solved.

<select id="sel_max" name="sel_max" style="width:83px" class="validate[required,funcCall[checkMinMax]]" >
jquery.validationEngine.js :
window.checkMinMax = function(field, rules, i, options) {
var minVal = parseInt($("#sel_min").val(), 10);
var maxVal = parseInt($("#sel_max").val(), 10);
var bothHaveValues = !isNaN(minVal) && !isNaN(maxVal);
if (bothHaveValues) {
if (minVal > maxVal) {
return options.allrules.cmm.alertText2;
}
else if (maxVal < minVal) {
return options.allrules.cmm.alertText;
}
}
};
jquery.validationEngine-en.js :
"cmm": {
"alertText": "* Max value < Min value!",
"alertText2": "* Min value > Max value!"
},

Related

check if user inserted value higher then 0 with vanilla js

I am creating a custom js validator from scratch, without the use of any libraries.
I want to validate a numeric input by checking if the user-inserted content in the input tag is great than 0:
<label>Price
<input type="text" id="price" name="price">
</label>
Attempt:
function price()
{
if (#price.value>0)
console.log('0.');
else
console.log('Incorrect');
}
Would this not work:
if(price.value.match(/^[0-9]+$/) && +(price.value) > 0){
im not quite sure what the hash symbol is being used for so i removed it in my example. Unless you are trying to find the ID in which you would have to look for the element like so:
var price = document.querySelector("#price");
function price()
{
var price = document.getElementById("#price"); // get the element
if (isNaN(price.value) || price.value <= 0) // if the value is not a number or is less than 0
console.log('Incorect');
else // otherwise
console.log('Correct');
}
How about some thing like that
var price = document.getElementById("price").value;
if (parseInt(price) > 0 && !isNaN(price)))
{
// then do something
}
else
{
// else do something
}

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

format number to price

I have seen a few of these jquery things going on, and just wondered if there was a simple number formatting script.
Essentially, all we wish to do, is format ( client side ) for checking purposes only, the number entered in a field. To show somewhere else on the page ( presumably in a div ) the formatted price they entered.
So lets say, field
input id="price" name="price" size="50" type="text" class="medium" /
And they enter 1234560
I want to show somewhere else on the page, :
You Entered : $1,234,560.00 as the price. Is this correct ?
This is only for visual purposes only. Alternatively, changing the value of what they type and formatting it "live" could be an option, however the value we want to send to the db is pure numerics, ie: 1234560
Setup a function like this one
Javascript format currency
function CurrencyFormatted(amount) {
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if(s.indexOf('.') < 0) { s += '.00'; }
if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
return s;
}
Then set an onchange for jQuery something like this
jQuery(document).ready(function(){
jQuery('#price').change(function(){
jQuery('#mydivsomewhere').val(CurrencyChange(jQuery('#price').val()));
});
});
Not sure if that is 100% correct, haven't tested it. But should call CurrencyFormat whenever the text in your input box changes. Should pass in the val of the textbox with id of price and set a div of id mydivsomewhere with the formatted value.

Javascript: set label text

I'm trying to implement a generic function for a form with several fields in the following format.
<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, LblTextCount)">
</textarea>
And the following JavaScript:
function checkLength(object, maxlength, label) {
charsleft = (maxlength - object.value.length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
object.value = object.value.substring(0, maxlength-1);
}
// I'm trying to set the value of charsleft into the label
label.innerText = charsleft;
document.getElementById('LblTextCount').InnerHTML = charsleft;
}
The first part works fine, but I'm not able to set the charsleftvalue into the label. What am I doing wrong?
Please note that I'm looking for a dynamic approach instead of hard coding the label name into the JS function. JQuery would be fine too :)
Solution - thanks to all!
HTML
<label id="LblTextCount"></label>
<textarea name="text">
</textarea>
JS
$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});
function checkLength(obj, maxlength, label) {
var charsleft = (maxlength - obj.val().length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}
// set the value of charsleft into the label
$(label).html(charsleft);
}
InnerHTML should be innerHTML:
document.getElementById('LblAboutMeCount').innerHTML = charsleft;
You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:
$(document).ready(function() {
$('textarea[name=text]').keypress(function(e) {
checkLength($(this),512,$('#LblTextCount'));
}).focus(function() {
checkLength($(this),512,$('#LblTextCount'));
});
});
You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:
function checkLength(obj, maxlength, label) {
charsleft = (maxlength - obj.val().length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
obj.val(obj.val().substring(0, maxlength-1));
}
// I'm trying to set the value of charsleft into the label
label.text(charsleft);
$('#LblAboutMeCount').html(charsleft);
}
So if you apply the above, you can change your markup to:
<textarea name="text"></textarea>
you are doing several things wrong. The explanation follows the corrected code:
<label id="LblTextCount"></label>
<textarea name="text" onKeyPress="checkLength(this, 512, 'LblTextCount')">
</textarea>
Note the quotes around the id.
function checkLength(object, maxlength, label) {
charsleft = (maxlength - object.value.length);
// never allow to exceed the specified limit
if( charsleft < 0 ) {
object.value = object.value.substring(0, maxlength-1);
}
// set the value of charsleft into the label
document.getElementById(label).innerHTML = charsleft;
}
First, on your key press event you need to send the label id as a string for it to read correctly. Second, InnerHTML has a lowercase i. Lastly, because you sent the function the string id you can get the element by that id.
Let me know how that works out for you
EDIT Not that by not declaring charsleft as a var, you are implicitly creating a global variable. a better way would be to do the following when declaring it in the function:
var charsleft = ....
For a dynamic approach, if your labels are always in front of your text areas:
$(object).prev("label").text(charsleft);

Categories

Resources