Javascript Promises Project to Handle Client Side HTML5 Form Fields Validation With Custom Error Messages in Browser Full Project For Beginners

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Simple For Validation</h1>
    <label for="name">Enter your name</label>
    <form id="form">
    <input type="text" id="name" placeholder="Enter your name">
    <input type="password" id="password" placeholder="Enter your password">
    <button id="button">Submit</button>
    </form>
</body>
<script>
    let validate = function (name, password) {


return new Promise((resolve, reject) => {
    if (name == "") {
        reject("Please enter the name")
    } else if (password == "") {
        reject("Please enter the password")
    } else if (password.length < 6) {
        reject("Password should be atleast 6 characters long")
    } else {
        resolve("Form is validated")
    }
})

}

let button = document.getElementById('button')

button.addEventListener('click', (e) => {

let name = document.getElementById('name').value

let password = document.getElementById('password').value

e.preventDefault()

validate(name, password)
    .then((message) => {
        alert(message)
    })
    .catch((error) => {
        alert(error)
    })


})
</script>
</html>

Leave a Reply