<!DOCTYPE html>
<
head
>
<
title
>Example 2</
title
>
<
script
src
=
</
script
>
<
style
>
input {
padding: 10px;
margin: 10px;
}
.error-message {
color: red;
margin-top: 5px;
}
.success-message {
color: green;
margin-top: 5px;
}
h1 {
color: green;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksforGeeks</
h1
>
<
h3
>Using Focus and Blur Events</
h3
>
<
label
for
=
"phoneNumber"
>Phone Number:</
label
>
<
input
type
=
"text"
id
=
"phoneNumber"
placeholder
=
"Enter phone number"
>
<
button
id
=
"clearBtn"
>Clear</
button
>
<
div
class
=
"error-message"
id
=
"errorMessage"
></
div
>
<
div
class
=
"success-message"
id
=
"successMessage"
></
div
>
<
script
>
$(document).ready(function() {
$('#clearBtn').on('click', function() {
$('#phoneNumber').val('').attr('placeholder', 'Enter phone number');
$('#errorMessage, #successMessage').empty();
});
$('#phoneNumber').on('focus', function() {
$('#successMessage').empty();
});
$('#phoneNumber').on('blur', function() {
let inputValue = $(this).val();
let phoneRegex = /^\d{3}-\d{3}-\d{4}$/;
if (inputValue.length === 0) {
$(this).attr('placeholder', 'Enter phone number');
$('#errorMessage').text('Phone number is required.');
} else if (!phoneRegex.test(inputValue)) {
$(this).attr('placeholder', 'Enter phone number');
$('#errorMessage').text('Invalid phone number format. Use XXX-XXX-XXXX.');
} else {
$(this).removeAttr('placeholder');
$('#errorMessage').empty();
$('#successMessage').text('Valid phone number!');
}
});
});
</
script
>
</
body
>
</
html
>