$("#myform").validate({
submitHandler: function (form) {
var cboxes = ($('input:checkbox:checked').filter(":checked").length);
var nboxes = ($(":checkbox:not(:checked)").length);
var flag = false;
if ((cboxes > 0) && (nboxes > 0)) {
flag = confirm('You have Checked only few locations among the List. \n Are you sure, you do not want to Prescribe from the other locations? ');
} else if (cboxes == 0) {
alert('Please select atleast One Address \n Where you would prefer to prescribe from.');
}
else {
flag = true;
}
return flag;
}
});
When the Confirm box pop up if I clicks ok it should accept the submit, but it is not.
Can anyone tell me why is this happening?
Replace return flag with form.submit.
$("#myform").validate({
submitHandler: function (form) {
var cboxes = ($('input:checkbox:checked').filter(":checked").length);
var nboxes = ($(":checkbox:not(:checked)").length);
var flag = false;
if ((cboxes > 0) && (nboxes > 0)) {
flag = confirm('You have Checked only few locations among the List. \n Are you sure, you do not want to Prescribe from the other locations? ');
} else if (cboxes == 0) {
alert('Please select atleast One Address \n Where you would prefer to prescribe from.');
}
else {
flag = true;
}
if(flag)
form.submit();
}
});
If you're not using AJAX, this is the way described in the .validate() docs.
Related
I have 2 address entries on my form. I also have 2 radio buttons to designate the "preferred" mailing address.
I'm attempting to validate these 2 and am not really sure if I'm doing it correctly. It seems to work if I have both addresses filled but I can't seem to get it to validate correctly if one of the addresses isn't filled.
Here's the javascript that does the validation:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
$("#" + prefs[i]).prop('checked', false);
$("#MailPrefBusi").validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
$("#MailPrefBusi").validationEngine({promptPosition : "bottomRight", scroll: true}).validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
}
return true;
}
I'm using jQueryValidationEngine but it also doesn't correctly validate them. I only use it to show the validation error for these fields.
Here is the criteria:
If the MailPrefBusi is checked, then the BusinessAddress1 must be filled in.
If the MailPrefHome is checked, then the HomeAddress1 must be filled in.
If no MailPrefxxx is checked, show error. If no xxxAddress1 is filled, Show error.
It looks like your second if statement if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) { is returning false when you don't want it to. You should be able to accomplish what you want using this:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
// enhanced validation function call here
return false;
}
}
//if the user hasnt checked anything, you can remove this if the form should validate without the user having to set a radio button
if(!$("#MailPrefBusi, #MailPrefHome").is(":checked")) {
// enhanced validation function call here
return false
}
return true;
}
You can see it working at this JS Fiddle: https://jsfiddle.net/h0vj9r35/
Hope that helps!
If you are trying to figure out whether the corresponding fields are filled based on checkbox values in a scenario where you have n no. of checkboxes and fields and would like to avoid hardcoding of values, you may use the following:
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
var allEmpty = false;
var valueError = ""
for (i = 0; i < 2; i++)
{
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
if(!$("#"+prefs[i]).is(":checked"))
valueError += prefs[i] + "," ;
else if($("#"+field[i]).val() == "")
valueError += field[i];
allEmpty = true;
}
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "")
{
$("#" + prefs[i]).prop('checked', false);
allEmpty = false;
alert("Need to enter " + field[i]);
return false;
}
if((i == 1) && allEmpty)
{
alert("You need to select " + valueError);
return false;
}
}
return true;
http://jsfiddle.net/n0303qd6/1/
The confirmation popup always return true. Please advice the correction needed.
$('#btnDelete').click(function () {
var check = false;
var aCheckbox = document.getElementsByTagName('input');
for (var i = 0; i < aCheckbox.length; i++) {
if (aCheckbox[i].type === 'checkbox' && aCheckbox[i].checked) {
check = true;
}
}
if (check === true) {
return jConfirm('Do u really want to delete?', 'Confirmation');
} else {
jAlert("Please select serial number", 'Alert');
return false;
}
});
Hope this help :
if (check === true) {
var answer = confirm('Do u really want to delete?', 'Confirmation');
if(answer)
return true;
else
return false;
}
else {
jAlert("Please select serial number", 'Alert');
return false;
}
Yes it creates problem you need to use third parameter as callback function of jconfirm like,
if (check === true) {
jConfirm('Do u really want to delete?', 'Confirmation', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
return false;
} else {
.....
Also remove extra closing }); from your code, see last two lines.
I'm currently using JavaScript code to validate a text field when the user types in letters a-z.
The script shows a tick if this is valid and a cross if its not. Now I am trying to add to the code to say check that the letters meet a minimum length of at least 4 characters, and if the min characters is met then show the tick and if the text is under the min character length show the cross.
How can I adjust my script to check the minimum length of the characters entered? Also can someone show me how I can allow '-' to be allowed in my validation?
script:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
if (reg.test(CnameField.value) == false)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
tried:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false)
if(input.value.length>!=len.min) return flase;
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
Almost there but you have a few syntax issues, so I've created an example test script for you:
function validateValue(value) {
var reg = /^[A-Za-z]+$/g;
var len = {min:4,max:60};
if (!reg.test(value)) {
console.log('didn\'t match regex');
return false;
}
if (value.length < len.min || value.length > len.max) {
console.log('incorrect length: ' + value);
return false;
}
console.log('correct length: ' + value);
return true;
}
validateValue('teststring');
Notice how I have set up the regex test, removing the == false? It's not needed because either false or array is returned. A true test will return true if anything other than null or false is returned.
Try this
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false) {
if(input.value.length<len.min)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
const validateCname = value => value.length < 4 ? `success message` : `error message`
function validateCname(value1)
{
var k = value1;
if(k.length<4){
//Your code if length is less than 4
}else{
//Your code if length is more than 4
}
}
I am having trouble validation a form and staying on the same page. Below is my javascript validation which is working as i get popups.
function valueChecks(input){
var reqdFields = false;
var ncFields = false;
var catCheck = false;
var refCheck = false;
var dtCheck = false;
var retval = false;
reqdFields = checkRequiredFields(input) ;
ncFields = checkNonComplianceFields(input);
catCheck = checkCat();
refCheck = checkRef();
dtCheck = subDate();
var mesgNo="0";
if (reqdFields == true){
mesgNo="0";
} else { mesgNo="1";
}
if (catCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"2";
}
if (refCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"3";
}
if (dtCheck == true){
mesgNo=mesgNo+"0";
} else { mesgNo=mesgNo+"4";
}
if (ncFields == true){
mesgNo=mesgNo+"0";
} else {mesgNo=mesgNo+"5";
}
if (mesgNo =="00000"){
retval=true;
}
else if ((mesgNo =="10000")||(mesgNo =="12000")||(mesgNo =="12300")||(mesgNo =="12340")||(mesgNo =="12345")||(mesgNo =="10300")||(mesgNo =="10340")||(mesgNo =="10040")){
retval = false;
alert("Please check that you have filled in all the Mandatory Fields");
}
else if ((mesgNo =="02000")||(mesgNo =="02300")||(mesgNo =="02040")||(mesgNo =="02340")||(mesgNo =="02345")){
retval = false;
}
else if ((mesgNo =="00300")||(mesgNo =="00340")||(mesgNo =="00345")){
retval = false;
alert ("Please enter at least one Reference Value (File Number, STT or BL Number)");
}
else if ((mesgNo =="0004")||(mesgNo =="00045")){
retval = false;
alert ("The Incident Date must be less than or equal today's Date");
}
else if ((mesgNo =="0005")){
retval = false;
alert ("Please enter at least one Non Conforming Party");
}
return retval;
}
And this is how i declare my form.
<html:form action="/qaeditsrl" onsubmit="return valueChecks(this);" >
<input type=submit value="Submit" name="method" >
Can someone tell me why this is going wrong?
Try changing the submit button to input type=button.
Remove the onsubmit on the form, and add an id.
Then add onclick on the button doing all the checks,
if no errors were found use document.getElementById('formId').submit() for submitting;
I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...