I'm using jQuery Ketch-up plugin to validate my forms.
I need to validate a drop down box, Eg: if user select the drop down option 'select' it should fire the error saying 'Please select the language'.
Validate an email field but that email field is not a required one.
I tried to validate drop-down box using the following code as per the doc. but it says 'jq.ketchup is undefined'
//Drop down validation
var jq = $.noConflict();
jq.ketchup.validation('validateSelect', 'Please select the language', function(form, el, value)
{
if(this.contains(value.toLowerCase(), 'select'))
{
return false;
}
else
{
return true;
}
});
For my 2nd question there is no help on the doc.
jquery-ketchup plugin works properly for text and textarea inputs. To apply validation on select, use id of select input
Example:
select input:
html code:
= f.input :type, :prompt => "Select type", :collection => (some_collection), input_html: { id: "list_select" }
js code:
$.ketchup.validation('lselect', 'You have not selected type!', function(form, el, value) {
return value.length == 0 ? false : true
});
$("#form_id").ketchup({},{
'#list_select' : 'lselect'
});
To Validate email only if user entered any value, but not as required field, you need to override the validation provided by plugin as follows:
$.ketchup.validation('email', 'Must be a valid E-Mail.', function(form, el, value) {
return ($.trim(value).length > 0) ? this.isEmail(value) : true
});
Related
i am working on a form which has multiple steps so in each step when i click next it validate the current active step page with map function.
i want to achieve Use map function to validate each input and create border around the input which is invalid or empty on button click
why i am doing this is that i don't want to get the values of input one by one and apply conditions on them.
new to JS and jQuery. Any help will be appreciated
what i tried so far but no result only error
var getstep1 = $("#step1 :input").map(function(getinput)
{
if($(getinput).val() == '')
{
return $(this).css('width', '10px');
}
else
{
$(".next").click(function() {
divs.eq(now).hide();
now = (now + 1 < divs.length) ? now + 1 : 0;
divs.eq(now).show(); // show next
});
}
// return this.value;
}).get();
Don't take it that complicated. You can use a form validator plugin - Validator.js, you can download it here
Load the validator.js script into the document.
Load the multifield.js if you’d like to validate a form field containing multiple inputs.
Disable the native HTML5 data validation on your form.
...
Apply validators to the form fields using the following attributes:
required: is required?
pattern: ‘numeric’, ‘alphanumeric’, ‘url’, ‘phone’, ’email’, or custom regex.
data-validate-words: Specify the minimum amount of words for this field.
data-validate-length: Specify the length allowed for the field (after trim). For example: [3,10] means that the field can only have 3 or 10 characters.
data-validate-length-range: Specify the minimum and/or maximum number of chars in the field (after trim).
data-validate-linked: Specify the field which the current field’s value (the attribute is set on) should be compared to.
data-validate-minmax: Specify the minimum and/or maximum value.
Name
Occupation
Email
Confirm Email address
Number
Initialize the form validator on the form element and done.
var validator = new FormValidator({
// options here
});
Validate the form on submit (OPTIONAL).
document.forms.onsubmit = function(e){
var submit = true,
validatorResult = validator.checkAll(this);
console.log(validatorResult);
return !!validatorResult.valid;
};
Default settings to config the form validator.
var validator = new FormValidator({
// shows alert tooltip
alerts : true,
// custom trigger events
// e.g. ['blur', 'input', 'change']
events : false,
// predefined validators
regex : {
url : /^(https?://)?([\w\d-_]+.+[A-Za-z]{2,})+/?/,
phone : /^+?([0-9]|[-|' '])+$/i,
numeric : /^[0-9]+$/i,
alphanumeric : /^[a-zA-Z0-9]+$/i,
email : {
illegalChars : /[()<>,;:\/"[]]/,
filter : /^.+#.+..{2,6}$/ // exmaple email "steve#s-i.photo"
}
},
// default CSS classes
classes : {
item : 'field',
alert : 'alert',
bad : 'bad'
}
});
Default error messages.
texts : {
invalid : 'inupt is not as expected',
short : 'input is too short',
long : 'input is too long',
checked : 'must be checked',
empty : 'please put something here',
select : 'Please select an option',
number_min : 'too low',
number_max : 'too high',
url : 'invalid URL',
number : 'not a number',
email : 'email address is invalid',
email_repeat : 'emails do not match',
date : 'invalid date',
time : 'invalid time',
password_repeat : 'passwords do not match',
no_match : 'no match',
complete : 'input is not complete'
},
The form will look like this:
I'm using selectize for my drop down menus and I'm trying to do form validation. Each of the menus has class .code_select, and I want to know if an option has been selected on all of them. My code should determine if something is selected, and if not add the ID of the dropdown to an array called empty_fields. However, my dropdowns are all ending up in the array whether they have a selected option or not. This is my code:
$(".code_select").each(function(){
if ($(this).find('option:selected').length === 0) {
empty_fields.push($(this).attr("id")+'-selectized');
submitForm=false;
}
});
An example of one of the inputs:
<div class='col-4'>
<input type='text' class='form-control code_select' id='5-tree-Betpap-stdCodeSelect' name='5-tree-Betpap-stdCode' aria-label='Tree Metric Field 5 Standard Code select'>
</div>
And my selectize initialization:
// initialize newCodes selectize control
newCodesSelect[index] = $(this).selectize({
valueField: 'id',
labelField: 'label',
create: false,
hideSelected: false,
options: listOptions[listType],
searchField: 'label',
placeholder: "Choose " + listType + " codes (type to search)",
maxItems: 1,
});
//This stores the selectize object to a variable
newCodesSelectize[index] = newCodesSelect[index][0].selectize;
How do I determine if the select is still on the "placeholder" when my placeholder has a variable?
Thank you!
OK, here is what worked for me. I had to use .selectize-control as the selector and find if any of the items have data-attribute=null.
$('#nextBtn').click(function() {
console.log("Next Button - adding hidden fields");
//remove any left over error formatting
$('.requiredField').removeClass('requiredField');
var fld_text="";
$('#error-messages').html(fld_text);
// validate form before submit
var empty_fields=[];
var submitForm=true;
$(".code_description").each(function(){
if ($(this).val()==="") {
empty_fields.push($(this).attr("id"));
submitForm=false;
}
});
$(".selectize-control").each(function(){
if ($(this).find(".item").attr('data-value') == null) {
empty_fields.push($(this).prev("input").attr("id")+'-selectized');
}
});
empty_fields.forEach(function(element) {
if (element!=="undefined-selectized") submitForm=false;
});
if (submitForm===true) {
$('#nextForm').submit();
}
else {
fld_text="<p>Review required fields</p>";
$('#error-messages').html(fld_text);
empty_fields.forEach(function(element) {
if (element!=="undefined-selectized") $("#"+element).addClass("requiredField");
});
}
});
Currently working on input file error validation When i searched about the validation i have found jquery validation so i have started using it and again when i searched about how to validate the input file i have got some useful information from SO Based on that I have created error validation page for input file. With my current code I can able to upload pdf & Jpeg file and view the file but the validation was not happening if user click next button without uploading any file it should say you have 2 files missed if the user upload one file and he click next button it should say you have 1 file miss. I have tried giving required in the html input type field and tried giving required in jquery validation nothing was working.
Here is my jquery code
$(".attachForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors === 0 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).addClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).removeClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},rules: {
apt_code:"required",
apt_cer:"required",
checkfile:"required"
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
I tried changing the name in all field but no use
Here is the fiddle link for the detailed code
Kindly please suggest me. kindly guide as i am not getting any stuff :(
Thanks for looking the question.
You have to assign the unique name attribute to each <input type="file" class="checkfile">
<input type="file" class="checkfile" name="file_alpha">
<input type="file" class="checkfile" name="file_beta">
and then in rules you have to define both fields and make sure they are required
rules: {
file_alpha: {
checkfile: "required",
required: true,
},
file_beta: {
checkfile: "required",
required: true,
}
},
Fiddle
Correct Solution
Above solution will work because assigning the unique name and required rules set will trigger the validation but will not return the desired result because OP trying to validate the input with same name attribute and triggering the error counter according to number of invalid input fields.
Reason the validation not working in original code because no required rules
rules: {
checkfile:"required"
},
defined anywhere.
so work around is set required rules and add to inputs with same name attribute OR type using jQuery each() function
$("input[type=file]").each(function() {
$(this).rules("add", {
required: true,
});
});
and validation will work, errors will triggered with counter and on validating the input field, error counter decrease as like OP's desired output.
Fiddle Proper Working Example
I have a form with fields which are pre populated with data from database, as I need to change phone number according to new data format schema, I also need to immediately fired up validation for pre populate input fieldd.
My JS code is as follows:
Method to validate HR phone numbers according to new schema:
$.validator.addMethod("mobileHR", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^\+[0-9]{1,3}\.[0-9]{1,14}$/);
}, "Unesite broj u fromatu: +385.111234567");
And function calls:
$(document).ready(function () {
// initialize validation
$('.form-horizontal').validate({
// set immediate validation, on event code 9
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
},
rules: {
"contactdetails[Registrant][Phone]": {
required: true,
mobileHR: true
}
},
messages: {
"contactdetails[Registrant][Phone]": {
required: "Molimo unesite broj telefona"
}
}
});
});
Input field is like these, and value parameter is allready populated, as data is fetched from database.
<div class="controls">
<input kl_virtual_keyboard_secure_input="on" name="contactdetails[Registrant][Phone]" value="011123456" size="30" class="Registrantcustomwhois" type="text">
</div>
Now I want to warn a user editing data, even if he doesn't change data in desired input field, to update format of his phone number, so I basically want to call validate() function at the document has been loaded.
Fiddle with example is here.
after putting validation rules, on jQuery's ready, just add $('.form-horizontal').valid(); to validate form.
See Fiddle, updated accordingly
I have a form with a required phone number field that looks like this with the maskedinput plugin
(999) 999-9999
I want the jquery validation to ignore the literals in order to validate this. Also, i want the literals to be removed before the form is submitted. But if there is a validation error i still want the maskedinput plugin activated so the format looks correct for the user still.
I figure i could edit the regex for the validation but then when the form is submitted the literals will still be on there.
Let me know i need to explain this better.
Any Ideas? I'm pretty new to jquery and all so detailed solution would be great.
My javascript code is this
$(document).ready(function(){
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "US Phone Number Required");
$("#valform").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$("#error-message").show().text("Please correct the required field(s)");
} else {
$("#error-message").hide();
}
},
messages: {
phone: {
required: ""
}
},
rules: {
phone: {
required: true,
phoneUS: true
},
},
});
$("#phone").mask("(999) 999-9999",{placeholder:" "});
});
You could remove the other characters before submitting the form using js
This code will remove the forbidden character from the input as soon as its entered.
The input field has the class "numbers". This binds the "keyup" event to that input field and calls a function called "handleInputKeyUp"
$(".numbers").bind("keyup", handleInputKeyUp);
The function:
function handleInputKeyUp(e){
var temp = e.currentTarget.value;
temp = temp.replace(/[^\d-]/g, "");
e.currentTarget.value = temp;
}
This code removes all but digits and - from the input field.