I am trying to do from date, to date validation (todate > fromdate).
please check my html code
From Date <input type="text" placeholder="From Date" id="fromDate" min-view="1"
ng-change="getFromMonth(newcashbenifit.toDate, newcashbenifit.fromDate);"
name="cbFromdate" ng-model="newcashbenifit.fromDate" autoclose="true" bs-datepicker />
To Date<input type="text" placeholder="To Date" id="toDate" min-view="1"
ng-change="getToMonth(newcashbenifit.toDate, newcashbenifit.fromDate);"
class="form-control" name="cbTodate" autocomplete="off"
ng-model="newcashbenifit.toDate" bs-datepicker />
i am using below functions to validate this. please check below functions
$scope.getToMonth = function (selectedToMonth,selectedFromMonth){
if(selectedFromMonth > selectedToMonth ){
$scope.cashBenefitForm.cbTodate.$setValidity("message", false)
}else{
$scope.cashBenefitForm.cbTodate.$setValidity("message", true)
}
}
$scope.getFromMonth = function (selectedToMonth,selectedFromMonth){
if(selectedFromMonth > selectedToMonth ){
$scope.cashBenefitForm.cbFromdate.$setValidity("message2", false)
}else{
$scope.cashBenefitForm.cbFromdate.$setValidity("message2", true)
}
}
Validation is working well. please check below image.
validation working correctly. Now i changed From date as '04/2020'. in the occasion, to date validation still appear. it should remove, because now todate > fromdate. check attached image
how i do this validation correctly. ?
Related
I have multiple pairs of input fields for start and end dates:
#foreach (var exam in exams){
<input type="date" data-val="true" required id="StartDate" value="exam.StartDate">
<input type="date" data-val="true" data-val-endError="Can't be before start date" required>
}
I'm using jQuery's validator.AddMethod to validate that the end date is after the starting date:
$.validator.addMethod("endError",
function (value, element, params) {
var startDate = $("#StartDate").on('input').val();
if (value.toString() <= startDate) {
return false;
} else {
return true;
}
});
$.validator.unobtrusive.adapters.addBool("endError");
The problem is the validation is always comparing the end dates to the first starting date. I want each end date to be compared to it's relevant starting date.
I'm still a newbie in javascript but I know that this is probably caused by the id being the same for all the startDate inputs, which is illegal html.
Is there a way to fix this?
Thanks!
the problem with your code is you are referencing always the same id StartDate
so its normal the validation is always from the same startdate. When you have lot of same id the search of id stops always at the first.
#foreach (var exam in exams){
<input type="date" data-val="true" required id="****StartDate*****" value="exam.StartDate">
<input type="date" data-val="true" data-val-endError="Can't be before start date" required>
}
and you have the same id for different tag, its not good in html.
in your validator, you reference the StartDate id
var startDate = $("#StartDate").on('input').val();
one solution will be to create an id indexed :
#{int i=1;}
#foreach (var exam in exams){
<input type="date" data-val="true" required id="StartDate#(i)" value="exam.StartDate">
<input type="date" data-val="true" data-val-endError="Can't be before start date" required>
i++;
}
you adapt the validator to trap the right id.
i suggest you to create an attribute data-id for example, and you put the id of StarDate: so in validator you trap the id of right date
$.validator.addMethod("endError", function (value, element, params) {
var idstartDate = $(element).attr("data-id");
var startDate= $(idstartDate).on('input').val();
:
and you modify the loop:
#{int i=1;}
#foreach (var exam in exams){
<input type="date" data-val="true" required id="StartDate#(i)" value="exam.StartDate">
<input type="date" data-id="#StartDate#(i)" data-val="true" data-val-endError="Can't be before start date" required>
i++;
}
I guess I'm doing a trivial error somewhere but will be grateful if someone can spot it.
I am trying to validate a postcode in a form field once it has been typed in. Similar code works fine in PHP but I've spent hours and the JS does not seem to be executing whatever I do.
Here is part of the form (all within body tags):
<form name ="register" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
...
<script type="text/javascript" src="common.js">
</script>
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onchange="isValidPostcode(this.form)" required />
Here are versions of the javascript (stuffed with alerts just to print out something).
Version 1:
function isValidPostcode(form) {
alert("called");
var p = document.register.postcode.value;
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
Version 2 (is called without a parameter):
function isValidPostcode() {
alert("called");
var p = document.getElementById('postcode').value.replace(/\s/g,'');
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
I tried binding to other events but can't get a single alert out. Even exact reproduction of the examples is not working. Hope someone gives me an idea of what is wrong.
you should replace onchange with keyup and remove quotes from regex :)
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onkeyup="isValidPostcode(this.value)" required />
function isValidPostcode(value) {
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(value)) console.log("OK");
else console.log("This does not look a valid UK postcode...");
}
You should use the keyup event to do that and add the event using JS, not inline it.
postcodeRegEx is a regex, not a string, you need to remove quotes around it.
function isValidPostcode() {
var p = document.getElementById('postcode').value.replace(/\s/g, '');
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
document.getElementById("postcode").addEventListener("keyup", function() {
isValidPostcode();
});
<form name="register" method="post" action="" autocomplete="off">
<input id="postcode" type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' required />
</form>
I need to code a function in Javacript that updates the button colour and enables it when all fields are valid.
See picture below to understand the user interaction with the form
When the admin wants to update an user the update button needs to be green only if the following apply
At least one edit button is enabled. (When the edit button is enabled the respective fields is deleted and the user can write something)
The field must be validated in real time
If I uncheck the field the script has to revalidate the other open fields. For Instance if the open field is blank the button should be red but if I close the field and another field was enabled and filled with valid text (lets assume just 1 character means valid) the button from red should turn green
Could you please help me to figure this out. I think a solution is to use the JQuery keyup function but it is restricted only to one field. I need instead something more global.
Is there a way in javascript to create a global button listener than be useful for this scenario
In addition when I turn on the password checkbox two fields are enabled and the button should be valid only if password is valid and it matches with confirmed password
Please see below a brief summary of the jsp page
I have omitted the small icons of the password fields and the bootstrap part of the code
<sf:form class="form-horizontal"
role="form"
id="formsubmit"
method="POST"
action="${pageContext.request.contextPath}/updateprofile"
commandName="user">
<sf:input type="text" class="form-control" value="${user.username}" path="username" readonly="true"></sf:input>
<input type="checkbox" class="form-control" name="email-checkbox" checked />
<sf:input id="emailInput" type="text" class="form-control" path="email" placeholder="Type Email" name="email" disabled="true" />
<input type="checkbox" class="form-control" name="first-name-checkbox" checked />
<sf:input id="nameInput" type="text" class="form-control" placeholder="Type First Name" path="firstName" name="firstName" disabled="true" />
<input type="checkbox" class="form-control" name="last-name-checkbox" checked />
<sf:input id="surnameInput" type="text" class="form-control" placeholder="Type Last Name" path="lastName" name="lastName" disabled="true" />
<input type="checkbox" class="form-control" name="password-checkbox" checked />
<input id="password" type="password" class="form-control" name="password" placeholder="Insert Password" disabled>
<input id="confirmpassword" type="password" class="form-control" name="confirmpassword" placeholder="Confirm Password" disabled>
<button id="updateUserBtn" type="submit" class="btn btn-danger" data-loading-text="Creating User..." disabled>Update User</button>
</sf:form>
My first attemp with javascript is below and it works only for the password fields but it is not connected with the edit button
$("input[type=password]").keyup(
function() {
var ucase = new RegExp("[A-Z]+");
var lcase = new RegExp("[a-z]+");
var num = new RegExp("[0-9]+");
if ($("#password").val().length >= 8) {
$("#8char").removeClass("glyphicon-remove");
$("#8char").addClass("glyphicon-ok");
$("#8char").css("color", "#00A41E");
} else {
$("#8char").removeClass("glyphicon-ok");
$("#8char").addClass("glyphicon-remove");
$("#8char").css("color", "#FF0004");
}
if (ucase.test($("#password").val())) {
$("#ucase").removeClass("glyphicon-remove");
$("#ucase").addClass("glyphicon-ok");
$("#ucase").css("color", "#00A41E");
} else {
$("#ucase").removeClass("glyphicon-ok");
$("#ucase").addClass("glyphicon-remove");
$("#ucase").css("color", "#FF0004");
}
if (lcase.test($("#password").val())) {
$("#lcase").removeClass("glyphicon-remove");
$("#lcase").addClass("glyphicon-ok");
$("#lcase").css("color", "#00A41E");
} else {
$("#lcase").removeClass("glyphicon-ok");
$("#lcase").addClass("glyphicon-remove");
$("#lcase").css("color", "#FF0004");
}
if (num.test($("#password").val())) {
$("#num").removeClass("glyphicon-remove");
$("#num").addClass("glyphicon-ok");
$("#num").css("color", "#00A41E");
} else {
$("#num").removeClass("glyphicon-ok");
$("#num").addClass("glyphicon-remove");
$("#num").css("color", "#FF0004");
}
if ($("#password").val() == $("#confirmpassword").val()
&& ($("#confirmpassword").val() != 0)) {
$("#pwmatch").removeClass("glyphicon-remove");
$("#pwmatch").addClass("glyphicon-ok");
$("#pwmatch").css("color", "#00A41E");
} else {
$("#pwmatch").removeClass("glyphicon-ok");
$("#pwmatch").addClass("glyphicon-remove");
$("#pwmatch").css("color", "#FF0004");
}
if ($("#password").val().length >= 8
&& ucase.test($("#password").val())
&& lcase.test($("#password").val())
&& num.test($("#password").val())
&& $("#password").val() == $("#confirmpassword").val()
&& ($("#confirmpassword").val() != 0)) {
$("#updateUserBtn").removeClass("btn-danger");
$("#updateUserBtn").addClass("btn-success");
$("#updateUserBtn").prop('disabled', false);
} else {
$("#updateUserBtn").removeClass("btn-success");
$("#updateUserBtn").addClass("btn-danger");
$("#updateUserBtn").prop('disabled', true);
}
});
A keyup handler attached to the form element will be called for any field within it having a keyup event. That is because most events bubble up through all their ancestors and can be listened for at any level.
Small example as requested :)
$("form").keyup(
function() {
// your existing code here
});
If you want to target only specific inputs for the changes, you could use a delegated handler instead attached to the form (this one is using the specific form id):
$("#formsubmit").on('keyup', 'input[type=text],input[type=password]',
function() {
// your existing code here
});
This applies the selector at event time so is quite efficient, and also means the this value will be the control that changed (if that is useful to you).
As a general jQuery guideline, only run selectors once and save the element. This is faster & shorter and usually more readable. Also you can chain most jQuery functions together.
e.g.
var $password = $("#password");
var $8char = $("#8char");
if ($password.val().length >= 8) {
$8char.removeClass("glyphicon-remove").addClass("glyphicon-ok").css("color", "#00A41E");
I want to check whether confirm password matches with password or not, through onkeypress() function. It's not working.. Some of the part working like password length must be 6 character. But, I'm having problem.. when i'm typing value for confirm password.. it is showing div error message even after when it matches with the password value which i entered in password text. Please help. Here is my code.
<input type='password' class='Register-textbox Password' name="Password" onkeypress="RegistrationValidation()">
<input type='password' class='Register-textbox ConfirmPassword' name="ConfirmPassword" onkeypress="RegistrationValidation()">
<div class="ShowPasswordNotMatchesError" style="display:none;">
* Password Mismatch
</div>
<script>
function RegistrationValidation()
{
var PasswordVal=$('.Password').val();
var ConfirmPasswordVal=$('.ConfirmPassword').val();
if(PasswordVal!=ConfirmPasswordVal)
{
$('.ShowPasswordNotMatchesError').show();
}
}
</script>
When you are using jQuery, please make use of those functions. I have made the following changes:
Made the code unobtrusive.
Checked for the correctness on blur().
Checked only if the user has entered something.
Removed unnecessary braces.
Added reverse condition.
Try this way:
$(function () {
$(".Register-textbox").blur(function () {
var PasswordVal=$('.Password').val();
var ConfirmPasswordVal=$('.ConfirmPassword').val();
if(PasswordVal != ConfirmPasswordVal && ConfirmPasswordVal.length > 0 && PasswordVal.length > 0)
$('.ShowPasswordNotMatchesError').show();
else
$('.ShowPasswordNotMatchesError').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='password' class='Register-textbox Password' name="Password" />
<input type='password' class='Register-textbox ConfirmPassword' name="ConfirmPassword" />
<div class="ShowPasswordNotMatchesError" style="display:none;">
* Password Mismatch
</div>
I'm having two text boxes to store two dates. I want to call a javascript function upon entering date into the first and second textbox. That is as soonas I enter the date in second box I want to call the javascript function. I tried onchange but it is not calling the javascript function. Can you suggest me the right event to call the javascript function? Thanks in advance. I'm using smarty. My code is as follows:
<label>Created Date From</label>
<div class="form-element">
<input type="text" class="cal fl-left" name="from_date" id="frmDate" value="{if $data.from_date}{$data.from_date}{else}{/if}" maxlength="10" />
</div>
<label>Created Date To</label>
<div class="form-element">
<input type="text" class="cal fl-left" name="to_date" id="toDate" value="{if $to_date}{$to_date}{else}{/if}" maxlength="10" onchange="get_tests_by_date(); return false;"/>
</div>
Javascript code is as follows:
function get_tests_by_date() {
document.location.href = "view_tests.php?test_category_id="+document.getElementById('test_category_id').value+"&test_mode="+document.getElementById('test_mode').value+"&test_type="+document.getElementById('test_type').value+"&package_type="+document.getElementById('package_type').value+"&created_date_from="+document.getElementById('frmDate').value+"&created_date_to="+document.getElementById('toDate').value+"&page=1";
}
This is what i ended up doing years ago, no jquery in this code:
HTML:
<input name="FormStartDate" value="" maxlength="10" onkeydown="KeyDateNumCheck()"/>
<input name="FormEndDate" value="" maxlength="10" onkeydown="KeyDateNumCheck()"/>
JS:
//do not allow to input anything except the numeric characters, dashes, or slashes
function KeyDateNumCheck()
{
var iKeyCode = event.keyCode;
if ( (iKeyCode != 109) && (iKeyCode != 189) && (iKeyCode != 111) && (iKeyCode != 191) &&
( ((iKeyCode > 57)&&(iKeyCode < 96)) || (iKeyCode > 105) || (iKeyCode == 32)) )
event.returnValue = false;
}