How to calculate date of birth by age? - react-hooks

Have two fields in formik one for age and one for date of birth and one button and I want to calculate date of birth from age . if I give age and enter calculate button. I want to set date of birth. Have write one function but it doesn't work. Can you please help me to get correct answer. Here is following code.
const age = values.age;
const getDisplayDate = (date) => {
if (date === null || date === undefined || date === "") {
return null;
}
let d = typeof date === "string" ? new Date(date) : date;
const year = d.getFullYear() - age;
let month = d.getMonth() + 1;
let day = d.getDate();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
console.log(`day:${day}/month:${month}/year:${year}`);
return `${year}-${month}-${day}`;
};
Here is form :
<div className="form-group col-md-4">
<label htmlFor="age">Age</label>
<Field
type="text"
className={`form-control form-control-sm ${getError(basicInformationError,
basicInformationTouched, "age")
? "is-invalid"
: ""
}`}
id="age"
name="basicInformation.age"
value={basic.age}
placeholder="age"
/>
<ErrorMessage
name="basicInformation.age"
component="div"
className="invalid-feedback"
/>
</div>
<div className="form-group col-md-4">
<div className="row">
{/* <div className="col"> */}
<label htmlFor="date">Date Of Birth</label>
<Field
type="date"
className={`form-control form-control-sm ${getError(
basicInformationError,
basicInformationTouched,
"dateOfBirth"
)
? "is-invalid"
: ""
}`}
id="date"
name="basicInformation.dateOfBirth"
value={getDisplayDate(basic.dateOfBirth) || ""}
// onChange={(e) => setFieldValue(valu)}
placeholder="date"
/>
<ErrorMessage
component="div"
name="basicInformation.dateOfBirth"
className="invalid-feedback"
/>
{/* </div> */}
<button
type="button"
className="btn btn-sm btn btn-info mt-2"
onClick={getDisplayDate}
>
Calculate DOB
</button>
</div>
</div>
Output:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/8xaPn.png

const handleAgeChange = (event) => {
const {
target: { value }
} = event;
handleChange(event);
const date = new Date();
date.setFullYear(date.getFullYear() - Number(value));
setFieldValue("dateOfBirth", date.toLocaleDateString());
};
https://codesandbox.io/s/recursing-bogdan-miip7?file=/index.js
Does it help you?

Related

How do I properly send an array of separated strings using react Hooks and forms?

I'm using a react form and hooks to send a post to my backend that's running Spring boot. When I send the form information through axios post it sends a formatted JSON which is perfect, but one portion of the JSON needs to be an array of strings instead it sends one long String in the array. How can I format my code to send an array of string inputs and not one large string? I know my backend works as i've tested the end point using swaggerUi and Postman, The issue is the missile array sending back a single string array element instead of multiple strings. Jackson on the backend will only parse each individually declared string
.
import React, {useEffect, useState} from "react";
import {Link, useNavigate} from "react-router-dom";
import EmpireService from "../service/EmpireService";
const CreateOrder = () => {
const [empireName, setEmpireName] = useState("");
const [hullName, setHullName] = useState("");
const [shieldType, setShieldType] = useState("");
const [weaponType, setWeaponType] = useState("");
const [missiles, setMissiles] = useState([]);
const shipOrder ={empireName,hullName,shieldType,weaponType,missiles};
const saveOrder = (e) => {
EmpireService.createOrder(shipOrder).then((response)=> {
console.log(response.data);
}).catch(error => {
console.log(error);
})
}
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3 border-success">
<div className = "card-body ">
<form>
<div className = "form-group mb-2">
<label className = "form-label">Empire Name: </label>
<input
type = "text"
placeholder='Enter Empire name'
name = "empireName"
className='form-control border-success'
value = {empireName}
onChange = {(e) => setEmpireName(e.target.value)}>
</input>
</div>
<div className = "form-group mb-2">
<label className = "form-label">Hull Name: </label>
<input type = "text"
placeholder='Enter Hullname'
name = "hullName"
className='form-control border-success'
value = {hullName}
onChange = {(e) => setHullName(e.target.value)}
>
</input>
</div>
<div className = "form-group mb-2 ">
<label className = "form-label">Shield: </label>
<input type = "text"
placeholder='Enter Shield type'
name = "shieldType"
className='form-control border-success'
value = {shieldType}
onChange = {(e) => setShieldType(e.target.value)}
>
</input>
</div>
<div className = "form-group mb-2 ">
<label className = "form-label">Weapon: </label>
<input type = "text"
placeholder='Enter desired weapon'
name = "weaponType"
className='form-control border-success'
value = {weaponType}
onChange = {(e) => setWeaponType(e.target.value)}
>
</input>
</div>
<div className = "form-group mb-2 ">
<label className = "form-label">Missiles: </label>
<input type = "text"
placeholder='Enter desired missile'
name = "missiles"
className='form-control border-success'
value = {missiles}
onChange = {(e) => setMissiles([e.target.value])}
>
</input>
</div>
<button className='btn btn-success ' onClick={(e) => saveOrder(e)} >Submit</button>
<Link to = "/dawn-parts" className='btn btn-danger'>Cancel</Link>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
export default CreateOrder;
This is the raw JSON generated after submitting the form I need the missiles array to be separate strings not a single string.
{
"empireName": "Tano",
"hullName": "hull",
"shieldType": "phase_shield",
"weaponType": "ion_cannon",
"missiles": [
"voice_of_Grace, Vengeance_of_Ended_Dreams, plasma_missile"
]
}
My axios service function to connect to the order endpoint.
createOrder(shipOrder){
return axios.post(CREATE_ORDER_URL,shipOrder);
}

Google Places API Autocomplete, how to add a second address

I need to search two addresses on the same webpage, one for location, one for correspondence. The first Google API Address works fine, I then tried duplicating the function and form modifying it, but it doesn't populate the second address, it always tries to populate the first address, can anyone tell me where I am going wrong please? Thanks for your help.
function initMap() {
const componentForm = [
'street_number',
'route',
'location',
'locality',
'administrative_area_level_2',
'postal_code',
];
const autocompleteInput = document.getElementById('location');
const options = {
types: ['(cities)'],
componentRestrictions: { country: 'gb' }
};
const autocomplete = new google.maps.places.Autocomplete(autocompleteInput);
autocomplete.addListener('place_changed', function () {
const place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: \'' + place.name + '\'');
return;
}
fillInAddress(place);
});
function fillInAddress(place) { // optional parameter
const addressNameFormat = {
'street_number': 'short_name',
'route': 'long_name',
'locality': 'long_name',
'administrative_area_level_2': 'short_name',
'postal_code': 'short_name',
};
const getAddressComp = function (type) {
for (const component of place.address_components) {
if (component.types[0] === type) {
return component[addressNameFormat[type]];
}
}
return '';
};
document.getElementById('location').value = getAddressComp('street_number') + ' '
+ getAddressComp('route');
for (const component of componentForm) {
// Location field is handled separately above as it has different logic.
if (component !== 'location') {
document.getElementById(component).value = getAddressComp(component);
}
}
}
}
function initMapAddress2() {
const componentForm = [
'street_number',
'route',
'location',
'locality',
'administrative_area_level_2',
'postal_code',
];
const autocompleteInput = document.getElementById('location2');
const options = {
types: ['(cities)'],
componentRestrictions: { country: 'gb' }
};
const autocomplete2 = new google.maps.places.Autocomplete(autocompleteInput);
autocomplete2.addListener('place_changed', function () {
const place2 = autocomplete2.getPlace();
if (!place2.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: \'' + place2.name + '\'');
return;
}
fillInAddress(place2);
});
function fillInAddress(place2) { // optional parameter
const addressNameFormat = {
'street_number2': 'short_name',
'route2': 'long_name',
'locality2': 'long_name',
'administrative_area_level_22': 'short_name',
'postal_code2': 'short_name',
};
const getAddressComp = function (type) {
for (const component of place2.address_components) {
if (component.types[0] === type) {
return component[addressNameFormat[type]];
}
}
return '';
};
document.getElementById('location2').value = getAddressComp('street_number2') + ' '
+ getAddressComp('route2');
for (const component of componentForm) {
// Location field is handled separately above as it has different logic.
if (component !== 'location2') {
document.getElementById(component).value = getAddressComp(component);
}
}
}
}
<div class="card-container">
<div class="panel">
<div>
<img class="sb-title-icon" src="https://fonts.gstatic.com/s/i/googlematerialicons/location_pin/v5/24px.svg" alt="">
<span class="sb-title">Correspondence Address</span>
</div>
<input type="text" placeholder="Search Address" id="location" />
<input type="text" placeholder="" id="street_number" />
<input type="text" placeholder="" id="route" />
<input type="text" placeholder="" id="locality" />
<div class="half-input-container">
<input type="text" class="half-input" placeholder="" id="administrative_area_level_2" />
<input type="text" class="half-input" placeholder="" id="postal_code" />
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=****************Zv_k&libraries=places&callback=initMap&channel=GMPSB_addressselection_v1_cA" async defer></script>
<div class="card-container">
<div class="panel">
<div>
<img class="sb-title-icon" src="https://fonts.gstatic.com/s/i/googlematerialicons/location_pin/v5/24px.svg" alt="">
<span class="sb-title">Location Address</span>
</div>
<input type="text" placeholder="Search Address" id="location2" />
<input type="text" placeholder="" id="street_number2" />
<input type="text" placeholder="" id="route2" />
<input type="text" placeholder="" id="locality2" />
<div class="half-input-container">
<input type="text" class="half-input" placeholder="" id="administrative_area_level_22" />
<input type="text" class="half-input" placeholder="" id="postal_code2" />
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=****************Zv_k&libraries=places&callback=initMapAddress2&channel=GMPSB_addressselection_v1_cA" async defer></script>
For anyone else having the same issue, I found a solution here Multiple Address on same page

Aurelia validation nor working when data is pre-populated in the form

I have been unable to get the validation to work on an edit model-view that has data bound to it in the activate method of its view-model.
I have a created.ts which works on an object with the same fields. This file has almost the same code - the exception is that since this one is a create, no data needs to be loaded to it. In this case, the validation is working properly.
If I comment the code that loads the data for the edit model-view - in the activate method - the validation works properly.
Needless to say I am new to SPA, Aurelia and TypeScript and need some help!!
Below is the code in edit.ts
import { ContactRepository } from "./contactRepository";
import { autoinject } from "aurelia-framework";
import { ContactForEditDto } from "./contactForEditDto";
import { json } from "aurelia-fetch-client";
import { inject, NewInstance } from "aurelia-dependency-injection";
import { ValidationRules, ValidationControllerFactory, validateTrigger,
Validator } from "aurelia-validation";
#autoinject
export class Edit {
public saveStatusMessage: string;
public isSaved: number = -1;
private controller = null;
private validator = null;
public canSave: boolean = false;
constructor(public contactForEdit: ContactForEditDto, private repository:
ContactRepository, private controllerFactory: ValidationControllerFactory,
public contactFullName: string, validator: Validator) {
console.log("starting edit controller");
this.controller = controllerFactory.createForCurrentScope(validator);
this.controller.validateTrigger = validateTrigger.changeOrBlur;
this.validator = validator;
this.controller.subscribe(event => this.validateWhole());
ValidationRules
.ensure((c: ContactForEditDto) => c.contactFirstName)
.displayName("First Name")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactLastName)
.displayName("Last Name")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactEmailAddress)
.displayName("Email Address")
//.required().withMessage("\${$displayName} cannot be empty.")
.email().withMessage("\${$displayName} needs to be in a correct email address format.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactPhoneNumber)
.displayName("Phone Number")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(12).withMessage("\${$displayName} cannot have more than 12 characters.")
.matches(/\d{3}-\d{3}-\d{4}/).withMessage("'${$value}' is not a valid \${$displayName}. Please enter a phone in the format xxx-xxx-xxxx")
.on(ContactForEditDto);
}
// source https://www.jujens.eu/posts/en/2017/Jan/24/aurelia-validation/
workaround 3
validateWhole() {
this.validator.validateObject(this.contactForEdit)
.then(results => this.canSave = results.every(result => result.valid));
}
// Returning data from here because I can return a promise
// and let the router know when i have retrieved my initial data.
// Activate receives a params object as defined in the route.
activate(params) {
console.log("ACTIVATE ON EDIT PARAMS:" + params);
this.repository
.getById(params.id)
.then(data => {
console.log(data);
this.contactForEdit = data;
this.contactFullName = this.contactForEdit.contactLastName + ", " +
this.contactForEdit.contactFirstName; // This needs to come from a method
in
contact.
});
}
edit() {
this.saveStatusMessage = "";
this.isSaved = -1;
// This will be an edit
if (this.contactForEdit.contactId >= 1) {
this.repository
.update(this.contactForEdit)
.then(response => {
if (((response.status == 201) || (response.status == 204))
&& (response.ok == true)) {
this.isSaved = 1;
this.saveStatusMessage = "Successfully saved the contact";
}
else {
this.isSaved = 0;
//response.json().then(json => this.retVal = json);
//TODO: get more details about the error.
if (response.status == 400) {
this.saveStatusMessage = "Unable to save the contact. Please make sure that you entered correct values for every field and try again.";
}
else {
this.saveStatusMessage = "Unable to save the contact.";
}
}
});
}
}
clearContactFields() {
this.contactForEdit = new ContactForEditDto(-1, "", "", "", "");
}
}
Below is the code in edit.html
<template>
<form id="editContact" submit.delegate="edit()">
<!-- placeholder for status messages. If equal to 1 display it. If equals to
-1 or 1 hide this.-->
<div id="successStatusMessage" class.bind="isSaved == 1 ? 'visible' :
'hidden'">
<div id="divSuccessMessage" class="alert alert-success">
×
<!--<span class="glyphicon glyphicon glyphicon-ok" aria-hidden="true">
</span> TODO: How to get the glyphicon working? -->
<span class="sr-only"> Success:</span> ${saveStatusMessage}
</div>
</div>
<!-- placeholder for status messages. If equal to 0 is in error, so dislay error message. if equals to -1 or 1 hide this.-->
<div id="errorStatusMessage" class.bind="isSaved == 0 ? 'visible' : 'hidden'">
<!-- placeholder for status messages. -->
<div id="divErrorMessage" class="alert alert-danger">
×
<!-- <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> TODO: class="glyphicon glyphicon-exclamation-sign" how to get these in here for class? -->
<span class="sr-only"> Error:</span> ${saveStatusMessage}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">
<!--<div if.bind="isCreate">
"Create a Contact"
</div>
<div if.bind="!isCreate">
Edit ${contactForEdit.contactFirstName}
</div>-->
${ "Edit " + contactFullName }
</div>
</div>
<div class="panel-body">
<div class="form-horizontal">
<div class="form-group" validation-errors.bind="editFirstNameErrors"
class.bind="editFirstNameErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">First Name: </label>
<div class="col-md-10">
<input type="text"
placeholder="First Name"
class="form-control"
value.bind="contactForEdit.contactFirstName & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editFirstNameErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="editLastNameErrors"
class.bind="editLastNameErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">Last Name: </label>
<div class="col-md-10">
<input type="text"
placeholder="Last Name"
class="form-control"
value.bind="contactForEdit.contactLastName & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editLastNameErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="emailErrors"
class.bind="editEmailErrors.length ? 'has-error' : ''">
<label for="emailAddress" class="control-label col-md-2">Email: </label>
<div class="col-md-10">
<input id="emailAddress"
type="text"
placeholder="Email Address (format: email#domain.com)"
class="form-control"
value.bind="contactForEdit.contactEmailAddress & validate" /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editEmailErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="editPhoneErrors"
class.bind="editPhoneErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">Phone: </label>
<div class="col-md-10">
<input type="text"
placeholder="Phone Number (format: xxx-xxx-xxxx)"
class="form-control"
value.bind="contactForEdit.contactPhoneNumber & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editPhoneErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<button type="submit" class="btn btn-default ${canSave ? '' : 'disabled'}">
<!-- Look at click.dependent when there are child with buttons calling this.-->
Save
</button>
<!-- AA-10-17-17 - replaced with errors per input field. <ul for.bind="controller.errors">
<li repeat.for="error of controller.errors" style="color:red">
${error.message}
</li>
</ul>-->
</div>
</div>
</div>
</form>
<div>
<a route-href="route: home"
class="btn btn-default">
Back to list
</a>
</div>
</template>
I expect it's because of this code:
.getById(params.id)
.then(data => {
console.log(data);
this.contactForEdit = data;
your validation is against a ContactForEditDto object, but my guess is your repository is returning a JSON object cast to a ContactForEditDto, so it's not actually a class at all.
Try something like
console.log(data);
this.contactForEdit = new ContactForEditDto(data.id, data.firstname ..etc..);
or
console.log(data);
this.contactForEdit = Object.assign(new ContactForEditDto(), data);
We just had a similar problem and solved it by setting up our validations after assigning the remote data to our local field. In your code, you'd set up your validation rules after this.contactForEdit = data;

Not able to delete characters of cc card, expiration and security code of input field in firefox

Working on a ember app. I have this form that takes in name, cc number, expiration and security number. I am able to backspace on name however I cant delete any of the other content, and this only happens in Firefox.
<div class="form-group cc-name input-row {{if nameValid 'has-success'}}">
<label class="label label--sm">Name on Card</label>
{{input type="text" value=name class="form-control"}}
</div>
<div class="form-group cc-number input-row {{if numberValid 'has-success'}}">
<label for="cc-number" class="label label--sm">Credit Card Number</label>
{{input-credit-card-number number=number class="form-control"}}
<div class="card-type {{if type 'show' 'hide'}}">
{{#if type}}
{{inline-svg type class="icon icon--credit-card"}}
{{/if}}
</div>
</div>
<div class="input-row input-row--inline">
<div class="form-group cc-expiration input-col--50 {{if expirationValid 'has-success'}}">
<label class="control-label label--sm">Expiration</label>
{{input-credit-card-expiration month=month year=year class="form-control"}}
</div>
<div class="form-group cc-cvc input-col--50 {{if cvcValid 'has-success'}}">
<label class="control-label label--sm">Security Code</label>
{{input-credit-card-cvc cvc=cvc class="form-control"}}
</div>
</div>
This is the code I need to override:
import Ember from 'ember';
import hasTextSelected from 'ember-credit-cards/utils/has-text-selected';
import formatters from 'ember-credit-cards/utils/formatters';
import cards from 'ember-credit-cards/utils/cards';
var cardFromNumber = cards.fromNumber;
var computed = Ember.computed;
function inputValid(value) {
value = (value + '').replace(/\D/g, '');
var card = cardFromNumber(value);
if (card) {
return value.length <= card.length[card.length.length - 1];
} else {
return value.length <= 16;
}
}
export default Ember.TextField.extend({
classNames: ['input-credit-card-number'],
placeholder: '•••• •••• •••• ••••',
autocomplete: 'cc-number',
type: 'tel',
keyPress: function(e) {
var digit = String.fromCharCode(e.which);
console.log(digit);
if (!/^\d+$/.test(digit)) {
return false;
}
var el = this.$();
if (hasTextSelected(el)) {
return true;
}
var value = el.val() + digit;
return inputValid(value);
console.log(value);
},
value: computed('number', function(key, value) {
var number = this.get('number');
if (arguments.length > 1) {
number = value;
this.set('number', value);
}
return formatters.formatNumber(number);
})
});
This code works for me:
export default Ember.TextField.extend({
classNames: ['input-credit-card-number'],
placeholder: '•••• •••• •••• ••••',
autocomplete: 'cc-number',
type: 'tel',
keyPress: function(e) {
if (e.keyCode == 46 || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 27 || e.keyCode == 13){
return true;
}
var digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return false;
}
var el = this.$();
if (hasTextSelected(el)) {
return true;
}
var value = el.val() + digit;
return inputValid(value);
console.log(value);
},
value: computed('number', function(key, value) {
var number = this.get('number');
if (arguments.length > 1) {
number = value;
this.set('number', value);
}
return formatters.formatNumber(number);
})
});

jQuery Validator not working for upper validation

I am validating two sections of a webpage the first validation section validates however the second validator is not for some reason.
$(function(){
/* first validation - works*/
jVal = {
//validate firstName
'firstName': function(){
//appends #firstNameInfo with .info to body
$('body').append('<div id="firstNameInfo" class="info"></div>');
//create variables
var firstNameInfo = $('#firstNameInfo');
var ele = $('#firstName');
var patt = /^[a-zA-Z][a-zA-Z]{1,20}$/;
if(!patt.test(ele.val())) {
jVal.errors = true;
firstNameInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
firstNameInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//validate lastName
'lastName': function() {
$('body').append('<div id="lastNameInfo" class="info"></div>');
var lastNameInfo = $('#lastNameInfo');
var ele =$('#lastName');
var patt = /^[a-zA-Z][a-zA-Z]{1,20}$/;
if(!patt.test(ele.val())){
jVal.errors = true;
lastNameInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
lastNameInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//validate phone
'phone' : function(){
$('body').append('<div id="phoneInfo" class="info"></div>');
var phoneInfo = $('#phoneInfo');
var ele = $('#phone');
var patt = /^((\+?1-)?\d\d\d-)?\d\d\d-\d\d\d\d$/;
if(!patt.test(ele.val())) {
jVal.errors = true;
phoneInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
phoneInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//validate zipcode
'zip' : function() {
$('body').append('<div id="zipInfo" class="info"></div>');
var zipInfo = $("#zipInfo");
var ele = $('#content_form #zip');
var patt = /^\d\d\d\d\d$/;
if(!patt.test(ele.val())){
jVal.errors = true;
zipInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
zipInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//submit button code
'sendForm':function(){
if(!jVal.errors){
$('#content_form').submit();
}
},
};
$('#content_form #submit').click(function(){
var obj = $.browser.webkit ? $('body') : $('html');
jVal.errors = false;
jVal.firstName();
jVal.lastName();
jVal.phone();
jVal.zip();
jVal.sendForm();
return false;
$('#firstName').change(jVal.firstName);
$('#lastName').change(jVal.lastName);
$('#email').change(jVal.email);
$('#content_form #zip').change(jVal.zip);
});
/**** Second Validation Does Not work ******/
kVal ={
'zip' : function() {
$('body').append('<div id="Infozip" class="info"></div>');
var Infozip = $("#Infozip");
var ele = $('#form #zip');
var patt = /^\d\d\d\d\d$/;
if(!patt.test(ele.val())){
kVal.error = true;
Infozip.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
Infozip.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//submit button code
'send':function(){
if(!kVal.errors){
$('#form').submit();
}
},
};
$('#form button#submit').click(function(){
var obj = $.browser.webkit ? $('body') : $('html');
kVal.errors = false;
kVal.zip();
kVal.send();
return false;
$('#form #zip').change(kVal.zip);
});
}); /*main function closer*/
HTML FOR FIRST Validation -WORKING -
<div id="content_form">
<p>
<label class="block">
<input type="text" id="firstName" type="firstName" autocomplete="on" value="first name">
</label>
<label class="block">
<input type="text" id="lastName" type="lastName" autocomplete="on" value="last name">
</label>
<label class="block">
<input type="text" id="phone" type="phone" autocomplete="on" value="phone">
</label>
<label class="block">
<input type="text" id="zip" type="zip" autocomplete="on" value="zip code">
</label>
<button type="submit" id="submit" value="Submit" title="submit">submit</button>
</p>
</div><!-- end form -->
HTML FOR SECOND Validation
<div id="form">
<p>
<label class="block">
<input type="text" id="zip" type="zip" autocomplete="on" value="zip code">
</label>
<button type="submit" id="submit" value="CHECK NOW" title="check now">check now</button>
</p>
</div><!-- end form -->
You have the same id on both zip fields, which is probably causing your problems. The docs for the jQuery #id selector has this to say;
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM. This behavior
should not be relied on, however; a document with more than one
element using the same ID is invalid.
That is, your selection in $('#form #zip').change(kVal.zip); will not use the hierarchy under #form to find #zip, it will still find the first instance in the entire DOM.

Resources