I want to use jquery validate() rule to 2 cross fields. If either of the field is typed in the other one is also required. Also, once they are required there format for number field should be 1st 15 digits should be integer and date field should be mm/dd/yyyy format and date should be less than todays date.
//..
$("#adjustmentsFormID").validate({
rules: {
refTranNbr: "required",
refTranDate: "required"
},
messages: {
refTranNbr: {
required: function (element) {
if($("#refTranDate").val().length > 0){
return "Please enter the reference transaction number ";
} else if(!refNumChk($("#refTranNbr").val())){
return "Please enter a valid Reference Transaction Number";
} else {
return false;
}
}
},
refTranDate: {
required : function (element) {
var tdate = $("#refTranDate").val();
if($("#refTranNbr").val().length > 0){
return "Please enter a date for the Refering Transaction to complete this transaction.";
}else if((new Date() > new Date(tdate))) {
return "Please enter a reference transaction date less than today's date.";
}else{
return false;
}
}
},
});
..//
In both the cases the 1st condition for required field works. However for refNum field the 2nd condition which has refNumChk isnot working. Actually its not getting called. Similarly for refTranDate required field validation works however date > tDate is not getting checked. Not sure if this method would work or should i do something different for multiple conditions.
Your approach to jQuery validation is wrong, the messages is used to return only the error message in case of an validation error.
So the only validation you are doing is the required validation, you can add custom validation rules to solve this
jQuery(function($) {
jQuery.validator.addMethod("refNumChk", function(value, element, params) {
return this.optional(element) || /^\d{15}[A-Z]$/.test(value);
}, jQuery.validator.format("Enter a value in forat aa-999"));
jQuery.validator.addMethod("lessThanToday", function(value, element, params) {
return this.optional(element) || new Date() > new Date(value);
}, jQuery.validator.format("Value should be less than today"));
$("#adjustmentsFormID").validate({
rules: {
refTranNbr: {
required: true,
//refNumChk: true
pattern: /^\d{15}[A-Z]$/
},
refTranDate: {
required: true,
lessThanToday: true
}
},
messages: {
refTranNbr: {
required: "Please enter the reference transaction number",
pattern: "Please enter a valid Reference Transaction Number"
},
refTranDate: {
required: "Please enter a date for the Refering Transaction to complete this transaction.",
lessThanToday: "Please enter a reference transaction date less than today's date."
},
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
<form id="adjustmentsFormID" method="post" action="">
<div>
<input name="refTranNbr" />
</div>
<div>
<input name="refTranDate" />
</div>
<input type="submit" value="Save" />
</form>
Related
I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
Name:
<input type="text" name="name" id="name" /><br />
Surname:
<input type="text" name="surname" id="surname" /><br />
Email:
<input type="email" name="email" id="email" /><br />
Message:
<textarea name="Message" maxlength="3500"></textarea><br />
<button id="submit" onclick="validation()">Submit</button>
</form>
<script>
var name = $("#name").value;
var surname = $("#surname").value;
var email = $("#email").value;
var comments = $("#comments").value;
function validation() {
if (name == "" || surname == "" || email == "" || comments == "") {
document.myForm.name.setCustomValidity("Please fill out this field");
document.myForm.surname.setCustomValidity("Please fill out this field");
document.myForm.email.setCustomValidity("Please fill out this field");
document.myForm.comments.setCustomValidity("Please fill out this field");
} else {
document.myForm.name.setCustomValidity();
document.myForm.surname.setCustomValidity();
document.myForm.email.setCustomValidity();
document.myForm.comments.setCustomValidity();
}
}
</script>
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this
if (name == "" || surname == "" || email == "" || comments == "") {
name=document.getElementById('name')
name.setCustomValidity("Please fill out this field");
name.reportValidity()
}
else
name.setCustomValidity('');
name.reportValidity()
also you can consider using a helper function to use the element id dynamically
Update:
you can use this it will work
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
Name:
<input type="text" name="name" id="name" required="required"/><br />
Surname:
<input type="text" name="surname" id="surname" required="required" /><br />
Email:
<input type="email" name="email" id="email" required="required" /><br />
Message:
<textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
<button onlclick='validation()'>Submit</button>
</form>
<script>
function validate(inputID)
{
var input = document.getElementById(inputID);
var validityState_object = input.validity;
if (validityState_object.valueMissing)
{
input.setCustomValidity('Please fill out this field');
input.reportValidity();
}
else
{
input.setCustomValidity('');
input.reportValidity();
}
}
function validation() {
var name= document.getElementById('name').value
var surname=document.getElementById('surname').value
var email=document.getElementById('email').value
var message=document.getElementById('message').value
validate('name')
validate('surname')
validate('email')
validate('message')
if (name!=''&&surname!=''&&email!=''&&message!='') {
$('#myform').submit();
}
}
</script>
The easiest way to validate forms with jquery is to use jquery validate.
I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.
$('#frmsendemail').validate({ // Send Email Form
ignore: '.ignore',
rules: {
seFullname: {
required: true,
minlength: 2
},
seContact: {
required: true,
phonesUK: true,
},
seMail: {
required: true,
email: true
},
seMsg: {
required: true
},
seCaptchaStatus: {
required: function () {
// verify the user response
var thisresponse = grecaptcha.getResponse(seCaptcha);
if (thisresponse == "") {
return true;
} else {
return false;
}
}
}
},
messages: {
seFullname: {
required: "Please Enter Your Name",
minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
},
seContact: {
required: "Please Enter a contact number",
phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
},
seMail: {
required: "Please Enter Your Email Address",
email: "Your email address should be in the format of "username#domain.com""
},
seMsg: "Please Enter A Message",
seCaptchaStatus: "Please complete reCaptcha."
},
highlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
$(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
},
unhighlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
$(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
},
showErrors: function (errorMap, errorList) {
$(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
this.numberOfInvalids() +
' errors, see details below.</h6');
this.defaultShowErrors();
},
validClass: "border-success",
invalidClass: "border-danger",
errorClass: "border-danger",
errorElement: 'div',
errorLabelContainer: ".seerrors",
submitHandler: function () {
//Now that all validation is satified we can send the form to the mail script.
//Using AJAX we can send the form, get email sent and get a response and display a nice
//message to the user saying thank you.
//For Debugging
//console.log("Sending Form");
$.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
//do stuff with returned data here
//result = $.parseJSON(result);
console.log(result.Status);
if (result.Status == "Error") {
//Create message from returned data.
//This helps the user see what went wrong.
//If its a form error they can correct it,
//if not then they can see whats wrong and alert us.
var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries#cadsolutions.wales</p>';
// Show JConfirm Dialog with error.
$.confirm({
title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
content: message3,
type: 'red',
// Set Theme for the popup
theme: 'Material',
typeAnimated: true,
buttons: {
close: function () {}
}
});
The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)
I have an HTML text input called hours that is verified as a number through a knockout extender. If the user entering the hours has any whitespace after the number they enter, I would like to simply have this trimmed without getting notified that what they've entered for hours is not a number. For example, if they enter "2.5 ", this should be correct as I want the extra spaces trimmed automatically. How am I able to do this with what I have below? Thank you.
hours: ko.observable().extend({ number: true, required: true })
You can add a trimming functionality to observables, e.g. adding a custom function to ko.subscribable.fn as explained in another SO post:
ko.subscribable.fn.trimmed = function() {
return ko.computed({
read: function() {
return this();
},
write: function(value) {
this(value.trim());
this.valueHasMutated();
},
owner: this
}).extend({ notify: 'always' });
};
var vm = function () {
this.num = ko.observable().trimmed().extend({ number: true });
this.num(' 2 ');
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
<input type="text" data-bind="value: num" />
P.S. Don't be tempted to add a trim() call into Knockout validator plugin number rule:
// this is the original 'number' rule implemetation, with a 'trim()' call added to it
ko.validation.rules['number'] = {
validator: function (value, validate) {
if (!validate) { return true; }
return ko.validation.utils.isEmptyVal(value) ||
(validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value.trim()));
},
message: 'Please enter a number.'
};
... because you don't want the trimming to happen during validation, but much earlier, that is: during the writing.
I am using https://jqueryvalidation.org/ to validate my form on the frontend. The basic "if field is empty - validate" works OK.
But I'd like to the submit button to be initially disabled until a valid email address has been entered. I'd like the button to become enabled as soon as the field becomes valid (on keypress).
So basically I just need to remove the 'btn-disabled' class once its valid.
I'm struggling with the jQuery to add this function/method. Would be grateful if someone can help out.
Heres a slightly simplifed version: http://codepen.io/dagford/pen/kXJpEZ
$(document).ready(function(){
$("#reset-form").validate({
rules: {
emailaddress: {
required: true,
email: true
}
},
messages: {
email: "Please enter a valid email address"
}
});
});
you can check if the form is valid after entering the email address. Keep you button disabled by default and remove the disabled attribute once you validate the form.
$("#emailaddress").on("blur", function(){
if($("#reset-form").valid())
{
$("#btn-reset").removeAttr("disabled");
}
});
Code Pen : http://codepen.io/anon/pen/YWLjKX?editors=1010
You have attr for this
$('#button1, #button2').attr("disabled", true);
Check this :
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') { // write your code for valid email here
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>
This question already has answers here:
jQuery Validate Plugin - How to create a simple custom rule?
(8 answers)
Closed 8 years ago.
I am trying to override the functionality of 'required' and 'minlength' validators provided by jQuery Validator plugin. Following is my code:
jQuery(".form-cls").validate({
errorElement: "span",
errorClass: "error-msg",
rules: {
email:{
required:true,
email:true,
alreadyExistEmail: true
},
user_email:{
required:true,
email:true
},
password:{
required: function (element) {
return checkIfPasswordIsRequired();
},
minlength: function (element) {
return passwordLengthCheck(element);
}
}
}
});
function checkIfPasswordIsRequired()
{
if(jQuery("#facebook_id").length > 0 || jQuery("#linkedin_id").length > 0 || jQuery("#xing_id").length > 0) {
if(jQuery("#facebook_id").val() != "" || jQuery("#linkedin_id").val() != "" || jQuery("#xing_id").val() != "") {
return false;
}
}
return true;
}
function passwordLengthCheck(element)
{
if(element.value.length < 6)
{
return false;
}
else
{
return true;
}
}
Now here the first check on password field is working fine that is of 'required' but the second check is not working. If have checked it my console.log(element.value.length) and it gives the length of value in password field each time the value is changed/altered but depending on the condition in function passwordLengthCheck it never shows/displays error. Kindly help!!
To check field length, just add minlength attribute to the <input> tag, like
<input id="pw" name="pw" minlength="6" type="password">
To add some custom validation, use addMethod():
jQuery.validator.addMethod("func", function(value, element) {
return this.optional(element) || check expression here;
}
I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>