Validating Multiple Textbox Date with jQuery Validate - javascript

I'm trying to write a custom method to validate a date. The date however exists in three text boxes. Furthermore, there may be multiple instances of this date.
<div class="customDate">
<input class="month" id="dob_Month" maxlength="2" name="dob.Month" type="text" />
/
<input class="day" id="dob_Day" maxlength="2" name="dob.Day" type="text" />
/
<input class="year" id="dob_Year" maxlength="4" name="dob.Year" type="text" />
</div>
On submit, I'd like to validate any div containing the customDate class. I.e. make sure all boxes have been filled, make sure ranges are correct, etc. I'm using the following code:
$.validator.addMethod("customDate", function(element) { return false;}, "error message");
The validation function isn't firing however. What am I missing? Also, is there a better way to do this.
Note: I've stubbed out the functionality for the actual validation logic. I just need to know how to get the validation method to fire.

I have managed to create multiple field validation without use of a hidden field by following the guide at
http://docs.jquery.com/Plugins/Validation/multiplefields and amending it accordingly
might be overkill though :)
html code
<div class="whatever">
<!-- dob html -->
<div id="dobdate">
<select name="dobday" class="dateRequired" id="dobday">
<option value="">Day</option>
<option value="1">1</option>
</select>
<select name="dobmonth" class="dateRequired" id="dobmonth">
<option value="">Month</option>
<option value="January">January</option>
</select>
<select name="dobyear" class="dateRequired" id="dobyear">
<option value="">Year</option>
<option value="2010">2010</option>
</select>
<div class="errorContainer"> </div>
</div>
<br />
<div id="joinedate">
<!-- date joined html -->
<select name="joinedday" class="dateRequired" id="joinedday">
<option value="">Day</option>
<option value="1">1</option>
</select>
<select name="joinedmonth" class="dateRequired" id="joinedmonth">
<option value="">Month</option>
<option value="January">January</option>
</select>
<select name="joinedyear" class="dateRequired" id="joinedyear">
<option value="">Year</option>
<option value="2010">2010</option>
</select>
<div class="errorContainer"> </div>
</div>
<br />
<input name="submit" type="submit" value="Submit" class="submit" title="Submit"/>
</div>
jquery code
// 1. add a custom validation method
$.validator.addMethod("CheckDates", function(i,element)
{
// function with date logic to return whether this is actually a valid date - you'll need to create this to return a true/false result
return IsValidDate(element);
}, "Please enter a correct date");
// 2. add a class rule to assign the validation method to the relevent fields - this sets the fields with class name of "dateRequired" to be required and use the method youve set up above
$.validator.addClassRules({
dateRequired: { required:true, CheckDates:true}
});
// 3. add a validation group (consists of the fields you want to validate)
$("#myForm").validate(
{
submitHandler: function()
{
alert("submitted!");
},
groups:
{
dob: "dobyear dobmonth dobday", joined : "joinedyear joinedmonth joinedday"
},
messages: { dob : " ", joined : " " // sets the invidual errors to nothing so that only one message is displayed for each drop down group
},
errorPlacement: function(error, element)
{
element.parent().children(".errorContainer").append(error);
}
});
JavaScript code
function IsValidDate(_element)
{
// just a hack function to take an element, get the drop down fields within it with a particular class name ending with day /month/ year and perform a basic date time test
var $dateFields = $("#" + _element.id).parent();
day = $dateFields.children(".dateRequired:[name$='day']");
month = $dateFields.children(".dateRequired:[name$='month']");
year = $dateFields.children(".dateRequired:[name$='year']");
var $newDate = month.val() + " " + day.val() + " " + year.val();
var scratch = new Date($newDate );
if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date")
{
return false;
} else {
return true;
}
}

I would try triggering an event on form submit before the validation which appends the values from the individual day/month/year inputs together into a separate hidden input, and then validate the hidden input instead.

You add a hidden field
<input id="month" maxlength="2" name="month" type="text" />
<input id="day" maxlength="2" name="day" type="text" />
<input id="year" maxlength="4" name="year" type="text" />
<input id="birthday" name="birthday" type="text" />
then concatenate the values in the hidden, and validate that field.
$('#day,#month,#year').change(function() {
$('#birthday').val($('#day').val()+'/'+ $('#month').val()+'/'+ $('#year').val());
});
then validate the hidden value.

I'm pretty sure that the validation plugin only supports validating inputs, not arbitrary DOM elements. The elements function filters out anything that isn't an element as well as submit, reset, image buttons and disabled inputs.
What you'd want to do is have validators for month, day, and year. Month and day would need to reference each other's values in order to perform correct validation logic.

Related

How to cut short multiple if else statements in Javascript

I recently came across a situation where I was working on a huge form with atleast 60 fields and I wanted that form to only submit if all fields were filled and if not, I wanted to show a custom message (Sweetalert) for every field not filled.
For example, If first name was left empty, show the message "Please enter your first name", If country of residence was not selected, show them the message that "Please select your country of residence" so on and so forth.
While I was writing tons of if and else statements to match every field using document.getElementById(), this thought of not doing things right came into my mind. I tried searching the web for this but was unable to find a suitable way of doing such things. Can anyone suggest me a better way rather then writing if else statements of 100 lines ?
By adding a specific class to your form controls you'd be able to retrieve them and iterate through them in order to check which ones are not filled.
Let's say this is your form:
<form id="myForm" name="myForm" novalidate>
<div>
<label for="control_1">Label_1:</label>
<input type="text" id="control_1" name="control_1" class="control" />
</div>
<div>
<label for="control_2">Label_2:</label>
<input type="text" id="control_2" name="control_2" class="control" />
</div>
<div>
<label for="control_3">Label_3:</label>
<input type="text" id="control_3" name="control_3" class="control" />
</div>
<div>
<label for="control_4">Label_4:</label>
<select id="control_4" name="control_4" class="control">
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
</select>
</div>
<div>
<input type="submit" value="Submit!" />
</div>
</form>
Then you can use the .control class to retrieve all controls and check them:
function onSubmit(e) {
e.preventDefault();
const controls = document
.getElementById("myForm")
.querySelectorAll(".control");
controls.forEach(control => {
if (!isControlFilled(control)) {
console.log(control.id);
// Do whatever you want with control's id
}
});
}
// This is just for illustrative purposes
// Should be adapted to cover all control types
function isControlFilled(control) {
return control.value ? true : false;
}

Change Button Text After Validating Fields Are Completed

My form includes a search that takes about 10 seconds. The submit button is titled SEARCH and upon clicking I have set this up to change to SEARCHING. This is the code:
<input type=submit class=button
value= Search
onclick="javascript:formSubmit();this.value='Searching...'">
But now I need to validate that an email field and another field are completed so that the button text changes to SEARCHING only if validated.
I tried this, but it does not work:
<input type=submit class=button
value= Search
onclick="myFunction();javascript:formSubmit();this.value='Searching...'">
<script>
function myFunction() {
if ( document.getElementsByName('numberadults')[0].value == '0' )
alert('The number of adults must be more than zero!');
document.getElementById("myEmail").required = true;
document.getElementById("demo").innerHTML = "The required property was set. The email field must now be filled out before submitting the form.";
}
</script>
Here is the html of the two fields being validated:
<select name=numberadults class=cboStyleZ>
<option value=0 selected>
0
</option>
<option value=1>
1
</option>
<option value=2>
2
</option>
<option value=3>
3
</option>
<option value=4>
4
</option>
<option value=5>
5
</option>
<option value=6>
6
</option>
<option value=--->
---
</option>
</select>
<input type="email" id="myEmail" class=cboStyleZ1 name="eaddr"
placeholder="Your email is all we need">
<script>
function myFunction() {
//other statements if required
document.getElementById("search").value = "searching";
}
</script>
<input type=submit class=button id="search"
value="search";
onclick="myFunction()">
I think this code can help you
The following click handler:
onclick="myFunction();javascript:formSubmit();this.value='Searching...'"
doesn't indicate how the validation in myFunction would affect the form submission and the text change.
There are several ways to skin a cat here, but in general, you could rely on control structures like if or using short-circuit operators to change the execution flow based on the value of an expression that interests you (e.g.: the return value of myFunction())
HTML
onclick="if(myFunction()) { javascript:formSubmit();this.value='Searching...'} "
JS
function myFunction() {
if ( document.getElementsByName('numberadults')[0].value == '0' ) {
// ...
// Display what is wrong with the form to the user
// ...
return false;
}
return true;
}

Javascript onchange function not working on select tag

I made 2 input fields and 1 select field and I applied onchange() function to select tag which calls javascript and that script make calculation and show it in other two fields
but it is not working for some syntax or logic reasons. please take a look at my code ,any help would be appreciated.
<html>
<head>
<script type="text/javascript">
function update() {
var x = document.getElementsByName("n_person").value;
document.getElementsByName("m_income").value= x*5;
document.getElementsByName("y_income").value= x*4;
}
</script>
</head>
<body>
<div class="elist"> <span class="b_text"><span>*</span>Level 1:</span>
// here is select tag where I put onchage function <select class="ifield" name="n_person" onChange="update()">
<option value="" selected="selected">Choose no. of person referred</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
// These are teh input where resultant value will appear <input type="text" value="" placeholder="Your weekly Income..." name="m_income" id="weekly_income" class="field" readonly required />
<input type="text" value="" placeholder="Your day Income..." name="y_income" id="day_income" class="field" readonly required/>
</div>
<!--elist-->
</body>
</html>
See this fiddle
Updated JS
function update() {
var x = document.getElementsByName("n_person")[0].value;
document.getElementsByName("m_income")[0].value = x * 5;
document.getElementsByName("y_income")[0].value = x * 4;
}
The problem with your JS was you was not targetting the correct HTML elements using getElementsByName.
Please read more about it here
The method getElementsByName returns, as its name indicates, a list of elements with the specified name and not just one. In your case, the names are unique to the document and the method will return a list with just one value, but you'll still need to index this list. Therefore, you must change this:
var x = document.getElementsByName("n_person").value;
to
var x = document.getElementsByName("n_person")[0].value;
Do this also for the other uses of getElementsByName and your code will work.

Angular.js / Ng.select with ng.value

I have the following select:
<select selected="windows" ng-model="wdtype[4][$index]" id="inputEmail1" class="form-control">
<option>app1</option>
<option>app2</option>
<option>app3</option>
</select>
I want that every time that the user select option, the field inputName3 will be reflected. The field defines like this:
<input type="text" class="form-control" ng-model="wdname[4][$index]" id="inputName3" placeholder="Machine Name" disabled>
For example, the user select app1, so the name will be m-app1. If the user select app2, the name will be displayed: m-app2.
I don't see any trigger in angular which can help me in this case.
You can define values for options like this
<option value="m-app1">app1</option>
<option value="m-app2">app2</option>
<option value="m-app3">app3</option>
Or make it in a generic way. Define a function in scope that transforms selected value the way you need.
In controller:
$scope.getMachineName = function () {
if (wdtype[4][$index]) return '';
return 'm-' + $scope.wdtype[4][$index];
}
In template
<input type="text" class="form-control" value="{{getMachineName()}}"

Jquery validation plugin and switching required field

Yup, basically, I am building a web form that need to provide different required form and validation function fallow by selected country.
I am using
<script type="text/javascript" src=" jquery-1.3.2.min.js" charset="utf-8"></script>
<script type="text/javascript" src=" jquery.validate.js" charset="utf-8"></script>
and here is my JS code
<script type="text/javascript" charset="utf-8">
function updatRequreForm (STATE,ZIPCODE) {
$("#frm_verification").validate({
rules: {
'form[country]' : "required",
'form[state]' : {required: STATE},
'form[zip]': {required: ZIPCODE},
},
messages: {
'form[country]' : "This field is required.",
'form[state]' : "This field is required.",
'form[zip]': "This field is required.",
});
};
function setRequreForm () {
var _cs = $('#country_select')[0];
if ('US' != _cs.value)
{
$('#state_star')[0].innerHTML = '';
$('#zip_star')[0].innerHTML = '';
updatRequreForm (false,false);
}
else
{
$('#state_star')[0].innerHTML = '*';
$('#zip_star')[0].innerHTML = '*';
updatRequreForm (true,true);
}
};
$(document).ready(function() {
setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
</script>
Here is my HTML:
<form id="frm_verification" action="some.php" method="POST">
<label for="country_select"><sup>*</sup>Country:</label>
<select name="form[country]" id="country_select">
<option value="">- Select -</option>
<option value="US" selected="selected">United States</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
<label for="select-state"><sup id="state_star">*</sup>State/Province/Region:</label>
<span id="states_select">
<select id="select-state" name="form[state]">
<option value="">- Select -</option>
<option value="AK">Alaska</option>
</select>
</span>
<span id="states_text" style="display:none;">
<input type="text" name="form[state]" value="" id="state" />
</span>
<label for="zip_code"><sup id="zip_star">*</sup>ZIP/Postal Code:</label>
<input type="text" id="zip_code" name="form[zip]" value="" id="zip">
<input type="submit" value="Submit" id="submit_btn" class="submit">
</form>
Basically, what I need to create is:
1.When user select US on country selection, the State and Zip area become required.
2.When user select Zambia on country selection, the State and Zip area become non-required.
Problem:
When I first load the page and click the Submit button with empty field, the form successfully validate each fields and shows warning. However selecting of the Zambia, the validation is not working.
Guess:
I have removed “setRequreForm ();” on ready function like:
$(document).ready(function() {
//setRequreForm ();
$('#country_select').change(function(){
setRequreForm ();
});
});
And tried to select Zambia, and tried to validate the form and it works. So I think calling “validate()” twice causes error.
Well I stuck with this for a while. Please help me to figure this out, I will really appreciate that.
You can't call validate more than ones becouse you run validate plugin more than one and this lead to errors.
You can setup your validator like this:
$("#myform").validate({
ignore: ".ignore"
})
Ignore tells to validator: field which has ignore css class should not be validated.
When you change requirements then add to specified fields css class "ignore":
$("#field1").addClass("ignore");
otherwise remove this class:
$("#field2").removeClass("ignore");

Categories

Resources