How to validate pre populated input field with jQuery validate? - javascript

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

Related

Validate input field depends on other html elmement jQuery validate function

I m trying to validate to validate the input depends on other html element.
If the other html is empty it should validate the input and if not the not valid.
This is my HTML:
<input id="oka_rijkregister_last" name="oka_rijksregisternummer_last" type="text">
<span id="oka_rijkregister_last_BtnVal" class="error_msg"></span>
I have a separate function on input which validate the input data, if data is not correct it displays the error message in span element else remains empty.
Here is my JS code which i am trying to validate depends on span element.
$("#myform").validate({
rules: {
oka_rijksregisternummer_last : {
minlength: {
param:17,
depends: function (element) {
if($("#oka_rijkregister_last_BtnVal").html() === "") {
return true;
}
else {
return false;
}
}
}
}
}
});
My code is working till param 17 and rest it ignores.
Can anyone help with this?
Thanks in advance.

input file type error validation not working using jquery

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

jQuery Calculator - validation executes instead of calculator

I made a jQuery calculator that takes Fuel amount and Burn rate to give Time til empty to display on my screen. I also am using form validation.
When I click on the calculator button it runs form validation for some and tries to run the server-side code which is fine if I was clicking on the form submit button (and that button performs the way it should). But I have my calculator button "id" attribute and "name" attribute different than the form submit button. So I don't understand why when I click on the calculator button it tries to run form validation. In addition, it doesn't give me the total in the
$('#time-empty-field').val(time_empty);
field. Ideally, I want the calculator to show the total in the $('time-empty-field') and not run form validation.
I know my HTML is fine and from what I can see I don't see anything wrong with my jQuery. Maybe a different set of eyes can help on this. Any help would be much appreciated. Thanks!
$(function() {
$('#id').focus();
// To clear phone example when active
$('#phone').focus(function() {
var field = $(this);
if (field.val() == field.prop('defaultValue')) {
field.val('').css('color', 'black');
}
});
// Reveals System Report
$('#system-box input').click(function() {
if ($(this).attr('checked')) {
$('#system-report').slideDown('fast');
} else {
$('#system-report').slideUp('fast');
}
});
//Calculator
$('#calculator-submit-btn').submit(function() {
var fuel_amount = $('#fuel-amount-field').val();
var burn_rate = $('#burn-rate-field').val();
var time_empty = fuel_amount * burn_rate;
time_empty = time_empty.toFixed(2);
$('#time-empty-field').val(time_empty);
});
// Form validation plug-In
$('#form1').validate({
rules: {
id: {
required: true,
number: true
},
password: {
required: true
},
phone: {
required: true,
phoneUS: true
}
},
messages: {
id: {
required: "Please enter ID number."
},
password: {
required: "Please enter password."
},
phone: {
phoneUS: "Please enter a valid phone number."
}
}
});
});
$('#calculator-submit-btn').click(function() {
var fuel_amount = $('#fuel-amount-field').val();
var burn_rate = $('#burn-rate-field').val();
var time_empty = fuel_amount * burn_rate;
time_empty = time_empty.toFixed(2);
$('#time-empty-field').val(time_empty);
});
submit() can be used on submit forms only.
for more details chec jQuery API : http://api.jquery.com/submit/
Simply you cannot attach submit() event to a button , only to a form.

Add validation to HTML5 required fields

I am using HTML5's required attribute on my input elements and select boxes and PHP for validation.
How can I show an alert if the required fields are not filled in? I tried using onsubmit() but the form is processed anyway and no alert is shown.
If the user's browser supports html5, he cant submit the form if not all the required fields have been written into.
Generally, you can prevent a form from submitting in jQuery like so:
$('#yourformselector').submit(function(event) {
$(this).find('[required="required"]').each(function() {
if (!$(this).val().length) {
event.preventDefault();
return false;
}
});
});
If you are using a modern/newer web browser, your default browser alerts should automatically display.
Or try:
$(document).ready(function() {
$('form').submit(function() {
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
//if incomplete contains any elements, the form has not been filled
if(incomplete.length) {
alert('please fill out the form');
//to prevent submission of the form
return false;
}
});
});
You may use checkValidity(), it will try to validate with attributes like pattern, min, max, required, etc. Follow this link to go deeper here
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
alert('invalid input')
} else {
alert('valid input')
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

Remove literals from input value before validation and submit

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.

Categories