Input Type Date validation 18 years old below
Asked Answered
V

5

6

I'm having trouble with validation of input type="date". It shouldn't accept 18 years old below. Could you please help me? Thank you.

I google and search the forum I haven't found the answer. I tried to validate it in the next page using PHP but my professor told me I must validate it in the same page. Like onchange it must be validated.

<input type="date" name="bday" id="bday" value="">
Vampire answered 30/12, 2013 at 4:3 Comment(5)
Use javascript for the validationThrawn
Use jquery datepicker for that input fieldLetterperfect
time to learn about javascript Date objectRooftree
Yes Sir I'm trying to learn itVampire
how you want the validation to be? 18 years below in the sense?Emblem
S
3

make use of javascript. If you want to accept birthdate of only 18 years and above then try following javascript code. put onblur="return dobcheck()" in bday tag.

<script type="text/javascript">
function dobcheck()
{
    var birth = document.getElementById('bday')
    if(birth != "")
    {

        var record=document.getElementById('bday').value.trim();
        var currentdate=new Date();    
        var day1 = currentdate3.getDate();   
        var month1 = currentdate3.getMonth();
        month1++;     
        var year11 = currentdate3.getFullYear()-17;
        var year2= currentdate3.getFullYear()-100;   
        var record_day1=record.split("/");
        var sum=record_day1[1]+'/'+record_day1[0]+'/'+record_day1[2];  
        var current= month1+'/'+day1+'/'+year11;
        var current1= month1+'/'+day1+'/'+year2;
        var d1=new Date(current)
        var d2=new Date(current1)
        var record1 = new Date(sum);      
        if(record1 > d1)
        {

            alert("Sorry ! Minors need parential guidance to use this website");
            document.getElementById('bday').blur();
            document.getElementById('bday').value="";
            document.getElementById('bday').focus();
            return false;
        }
    } 
}
</script>

i hope that now you will get it...

Stress answered 30/12, 2013 at 4:14 Comment(1)
Sir I don't know how to use this. Here is my jsfiddle jsfiddle.net/92Y2L thank you so much sirVampire
Z
5

In case you are allowed to use HTML5, it is pretty simple. You can simply use the max attribute:

<input id="bday" type="date" max="1995-12-31" required="" />

In case you have to do it dynamic you can create the max attribute dynamically.

I made an example: http://jsfiddle.net/trixta/wpb54/ http://jsfiddle.net/trixta/wpb54/4/

Zannini answered 30/12, 2013 at 20:39 Comment(0)
S
3

make use of javascript. If you want to accept birthdate of only 18 years and above then try following javascript code. put onblur="return dobcheck()" in bday tag.

<script type="text/javascript">
function dobcheck()
{
    var birth = document.getElementById('bday')
    if(birth != "")
    {

        var record=document.getElementById('bday').value.trim();
        var currentdate=new Date();    
        var day1 = currentdate3.getDate();   
        var month1 = currentdate3.getMonth();
        month1++;     
        var year11 = currentdate3.getFullYear()-17;
        var year2= currentdate3.getFullYear()-100;   
        var record_day1=record.split("/");
        var sum=record_day1[1]+'/'+record_day1[0]+'/'+record_day1[2];  
        var current= month1+'/'+day1+'/'+year11;
        var current1= month1+'/'+day1+'/'+year2;
        var d1=new Date(current)
        var d2=new Date(current1)
        var record1 = new Date(sum);      
        if(record1 > d1)
        {

            alert("Sorry ! Minors need parential guidance to use this website");
            document.getElementById('bday').blur();
            document.getElementById('bday').value="";
            document.getElementById('bday').focus();
            return false;
        }
    } 
}
</script>

i hope that now you will get it...

Stress answered 30/12, 2013 at 4:14 Comment(1)
Sir I don't know how to use this. Here is my jsfiddle jsfiddle.net/92Y2L thank you so much sirVampire
K
3

I know it's too late :D But may be, it would help others :)

    $(function(){
        var dtToday = new Date();
    
        var month = dtToday.getMonth() + 1;// jan=0; feb=1 .......
        var day = dtToday.getDate();
        var year = dtToday.getFullYear() - 18;
        if(month < 10)
            month = '0' + month.toString();
        if(day < 10)
            day = '0' + day.toString();
    	var minDate = year + '-' + month + '-' + day;
        var maxDate = year + '-' + month + '-' + day;
    	$('#dob').attr('max', maxDate);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="dob">
Korns answered 2/2, 2017 at 10:31 Comment(1)
jQuery is superfluous here. Simply replace $(function(){/*…*/}) with document.addEventListener("DOMContentLoaded", function(){/*…*/} and $('#dob') with document.querySelector('#dob')Gorgerin
A
0
<?php 
        $year=(int)date("Y");
        $year-=18;
        $year=(String)$year;
        $year=$year.'-'.date("m").'-'.date("d");
        echo "<input type='date'  id='dob' name='dob' 
max='$year' required>";
        ?>
Anthonyanthophore answered 22/7, 2022 at 0:1 Comment(2)
This is too late but i find it much easier and simple . This may be useful for new ones : -) Its my own code : -)Anthonyanthophore
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Almatadema
P
0
import React, { useState } from 'react';
import { Row, Col } from 'react-bootstrap';
import './Form1.css';

function Form1() {
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        file: null,
        number: '',
        DOB: '',
        gender: '',
        username: '',
        password: '',
        repassword: '',
        city: '',
        state: '',
        zip: '',
        country: '',
        address: ''
    });

    const [errorMessage, setErrorMessage] = useState({});
    const [submissions, setSubmissions] = useState([]);
    const [isEditing, setIsEditing] = useState(false);
    const [currentEditIndex, setCurrentEditIndex] = useState(null);

    const calculateAge = (dob) => {
        const birthDate = new Date(dob);
        const today = new Date();
        let age = today.getFullYear() - birthDate.getFullYear();
        const monthDifference = today.getMonth() - birthDate.getMonth();
        if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    };

    const validateField = (name, value) => {
        let error = '';
        const nameRegex = /^[A-Za-z\s]{2,50}$/;
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        const phoneRegex = /^[6-9]\d{9}$/;
        const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
        const usernameRegex = /^[a-zA-Z0-9]{3,20}$/;
        const addressRegex =  /^[a-zA-Z0-9]{5,100}$/;
        const zipRegex = /^\d{5}(?:[-\s]\d{4})?$/;
        const cityRegex =  /^[A-Za-z\s]{3,30}$/;
        const stateRegex = /^[A-Za-z\s]{2,20}$/;
        const countryRegex = /^[A-Za-z\s]{5,60}$/;

        switch (name) {
            case 'name':
                if (!value) {
                    error = 'Name is required!';
                } else if (!nameRegex.test(value)) {
                    error = 'Please enter a valid name (2-50 alphabetic characters).';
                }
                break;
            case 'email':
                if (!value) {
                    error = 'Email is required!';
                } else if (!emailRegex.test(value)) {
                    error = 'Please enter a valid email address.';
                }
                break;
            case 'file':
                if (!value) {
                    error = 'File is required';
                } else if (!['image/jpeg', 'image/png'].includes(value.type) || value.size > 5 * 1024 * 1024) {
                    error = 'Please upload a valid file (jpg/png) with size up to 5MB.';
                }
                break;
            case 'number':
                if (!value) {
                    error = 'Please enter a valid number!';
                } else if (!phoneRegex.test(value)) {
                    error = 'Please enter a valid Indian phone number (10 digits).';
                }
                break;
            case 'DOB':
                if (!value) {
                    error = 'Please enter your date of birth';
                } else if (calculateAge(value) < 13) {
                    error = 'You must be at least 13 years old.';
                }
                break;
            case 'gender':
                if (!value) {
                    error = 'Please select your gender';
                }
                break;
            case 'username':
                if (!value) {
                    error = 'Username is required!';
                } else if (!usernameRegex.test(value)) {
                    error = 'Please enter a valid username (3-20 alphanumeric characters).';
                }
                break;
            case 'password':
                if (!value) {
                    error = 'Password is required';
                } else if (!passwordRegex.test(value)) {
                    error = 'Password must be at least 8 characters long and include at least one uppercase letter, one lowercase letter, one number, and one special character.';
                }
                break;
            case 'repassword':
                if (value !== formData.password) {
                    error = 'Passwords do not match.';
                }
                break;
                case 'city':
                if (!value) {
                    error = 'Please enter your city.';
                }
                 else if(!cityRegex.test(value)) {
                   error = 'Please enter a valid city name  (3-30 alphabetic characters).'; 
                }
                break;
            case 'state':
                if (!value) {
                    error = 'Please enter your state or province.';
                } else if (!stateRegex.test(value)) {
                  error = 'Please enter a valid state name  (2-20 alphabetic characters).'
                }
                break;
            case 'zip':
                if (!value) {
                    error = 'Zip/Postal is required';
                }
                 else if(!zipRegex.test(value)) {
                   error = 'Please enter a valid Zip/Postal (6 digits).'; 
                }
                break;
            case 'country':
                if (!value) {
                    error = 'Please enter your country.';
                } else if (!countryRegex.test(value)) {
                    error = "Please enter a valid country name  (2-60 alphabetic characters)."
                }
                break;
                case 'address':
                    if (!value) {
                        error = 'Please enter a valid address.';
                    } else if(!addressRegex.test(value)) {
                       error = 'Please enter a valid address (5-100 alphanumeric character)'; 
                    }
                    break;
            default:
                break;
        }
        return error;
    };

    const handleChange = (e) => {
        const { name, value, type, files } = e.target;
        const newValue = type === 'file' ? files[0] : value;
        setFormData({
            ...formData,
            [name]: newValue
        });

        const error = validateField(name, newValue);
        setErrorMessage({
            ...errorMessage,
            [name]: error
        });
    };

    const validateForm = (values) => {
        const errors = {};
        for (let field in values) {
            const error = validateField(field, values[field]);
            if (error) {
                errors[field] = error;
            }
        }
        return errors;
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        const errors = validateForm(formData);
        if (Object.keys(errors).length === 0) {
            if (isEditing) {
                const updatedSubmissions = submissions.map((submission, index) =>
                    index === currentEditIndex ? formData : submission
                );
                setSubmissions(updatedSubmissions);
                setIsEditing(false);
                setCurrentEditIndex(null);
            } else {
                setSubmissions([...submissions, formData]);
            }
            localStorage.setItem('submissions', JSON.stringify([...submissions, formData]));
            alert('Form submitted successfully!');
            handleReset();
        } else {
            setErrorMessage(errors);
        }
    };

    const handleReset = () => {
        setFormData({
            name: '',
            email: '',
            file: null,
            number: '',
            DOB: '',
            gender: '',
            username: '',
            password: '',
            repassword: '',
            city: '',
            state: '',
            zip: '',
            country: '',
            address: ''
        });
        setErrorMessage({});
    };

    const handleEdit = (index) => {
        setFormData(submissions[index]);
        setIsEditing(true);
        setCurrentEditIndex(index);
    };

    const handleDelete = (index) => {
        const updatedSubmissions = submissions.filter((_, i) => i !== index);
        setSubmissions(updatedSubmissions);
        localStorage.setItem('submissions', JSON.stringify(updatedSubmissions));
    };

    return (
        <>
            <div className="App">
                <h1>Form</h1>
                <fieldset>
                    <form onSubmit={handleSubmit}>
                        <Row className="">
                            <Col xs={12} >
                                <Row className="g-3 mb-6">
                                    <Col sm={6} md={6}>
                                        <label htmlFor="name">Name*</label>
                                        <input type="text" name="name" id="name" placeholder="Enter Your Name"
                                            value={formData.name} onChange={handleChange} required />
                                        {errorMessage.name && <p className="error text-danger">{errorMessage.name}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="email">Email*</label>
                                        <input type="email" name="email" id="email" placeholder="Enter Your Email"
                                            value={formData.email} onChange={handleChange} required />
                                        {errorMessage.email && <p className="error text-danger">{errorMessage.email}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="file">File*</label>
                                        <input type="file" name="file" id="file" placeholder="Upload Your File"
                                            onChange={handleChange} required />
                                        {errorMessage.file && <p className="error text-danger">{errorMessage.file}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="number">Phone Number*</label>
                                        <input type="tel" maxLength={10} name="number" id="number" placeholder="Your Contact"
                                            value={formData.number} onChange={handleChange} required />
                                        {errorMessage.number && <p className="error text-danger">{errorMessage.number}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="DOB">DOB*</label>
                                        <input type="date" name="DOB" id="DOB" placeholder="Date of Birth"
                                            value={formData.DOB} onChange={handleChange} required />
                                        {errorMessage.DOB && <p className="error text-danger">{errorMessage.DOB}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="username">UserName*</label>
                                        <input type="text" name="username" id="username" placeholder="UserName"
                                            value={formData.username} onChange={handleChange} required />
                                        {errorMessage.username && <p className="error text-danger">{errorMessage.username}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="password">Password*</label>
                                        <input type="password" name="password" id="password" placeholder="Enter Password"
                                            value={formData.password} onChange={handleChange} required />
                                        {errorMessage.password && <p className="error text-danger">{errorMessage.password}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="repassword">Re-password*</label>
                                        <input type="password" name="repassword" id="repassword" placeholder="Confirm Password"
                                            value={formData.repassword} onChange={handleChange} required />
                                        {errorMessage.repassword && <p className="error text-danger">{errorMessage.repassword}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="city">City*</label>
                                        <input type="text" name="city" id="city" placeholder="Enter City Name"
                                            value={formData.city} onChange={handleChange} required />
                                        {errorMessage.city && <p className="error text-danger">{errorMessage.city}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="state">State/Province*</label>
                                        <input type="text" name="state" id="state" placeholder="State/Province"
                                            value={formData.state} onChange={handleChange} required />
                                        {errorMessage.state && <p className="error text-danger">{errorMessage.state}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="zip">Zip/Postal Code*</label>
                                        <input type="tel" maxLength={7} name="zip" id="zip" placeholder="Zip/Postal"
                                            value={formData.zip} onChange={handleChange} required />
                                        {errorMessage.zip && <p className="error text-danger">{errorMessage.zip}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <label htmlFor="country">Country*</label>
                                        <input type="text" name="country" id="country" placeholder="Enter Country Name"
                                            value={formData.country} onChange={handleChange} required />
                                        {errorMessage.country && <p className="error text-danger">{errorMessage.country}</p>}
                                    </Col>
                                    <label htmlFor="gender">Gender*</label>
                                    <input type="radio" name="gender" id="male" value="Male" className='radio'
                                        checked={formData.gender === 'Male'} onChange={handleChange} required />Male
                                    <input type="radio" name="gender" id="female" value="Female" className='radio'
                                        checked={formData.gender === 'Female'} onChange={handleChange} required />Female
                                    <input type="radio" name="gender" id="other" value="Other" className='radio'
                                        checked={formData.gender === 'Other'} onChange={handleChange} required />Other  
                                    {errorMessage.gender && <p className="error text-danger">{errorMessage.gender}</p>}
                                    <Col sm={6} md={12}>
                                        <label htmlFor="address">Address*</label>
                                        <input type="text" name="address" id="address" placeholder="Your Address"
                                            value={formData.address} onChange={handleChange} required />
                                        {errorMessage.address && <p className="error text-danger">{errorMessage.address}</p>}
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <button type="button" onClick={handleReset}>Reset</button>
                                    </Col>
                                    <Col sm={6} md={6}>
                                        <button type="submit">{isEditing ? 'Update' : 'Submit'}</button>
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                    </form>
                </fieldset>
            </div>

            <br /><br />
            <div className='contain-table'>
                <table className="table table-striped">
                    <thead>
                        <tr>
                            <th>No.</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone No.</th>
                            <th>DOB</th>
                            <th>Gender</th>
                            <th>UserName</th>
                            <th>City</th>
                            <th>Country</th>
                            <th colSpan={2} className="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {submissions.map((submission, index) => (
                            <tr key={index}>
                                <td>{index + 1}</td>
                                <td>{submission.name}</td>
                                <td>{submission.email}</td>
                                <td>{submission.number}</td>
                                <td>{submission.DOB}</td>
                                <td>{submission.gender}</td>
                                <td>{submission.username}</td>
                                <td>{submission.city}</td>
                                <td>{submission.country}</td>
                                <td>
                                    <button onClick={() => handleEdit(index)} className="button">Edit</button>
                                    <button onClick={() => handleDelete(index)} className="button">Delete</button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </>
    );
}

export default Form1;
Pecan answered 22/5, 2024 at 13:16 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Almatadema

© 2022 - 2025 — McMap. All rights reserved.