190k views
0 votes
Write JavaScript code for the following functions:

a) checkDate that uses regular expressions to validate the format of a date.
The function returns true if the given date exactly matches dd/mm/ yyyy format. (e.g 16/04/2023)
function checkDate( str)
{

}
b) checkUserName that uses regular expressions to validate a username format.
The function returns true if the given username matches the following Criteria:
The username must be at least 3 characters long.
The username must be at most 10 characters long.
The username must start with an English letter, whether it is a lowercase or uppercase.
Only English letters (a-z and A-Z), numbers and underscores are allowed.
function checkUserName( str)
{

}

1 Answer

4 votes

Final answer:

The provided JavaScript code uses regular expressions to validate both a date format (dd/mm/yyyy) with the checkDate function and a username with specific criteria with the checkUserName function.

Step-by-step explanation:

To check if a date is in the format dd/mm/yyyy, you can use the following JavaScript code in the function checkDate:

function checkDate(str) {
var pattern = /^(0?[1-9]|[12][0-9]|3[01])\/(0?[1-9]|1[012])\/(\d{4})$/;
return pattern.test(str);
}

And to validate a username with the specified criteria, the checkUserName function can be defined like this:

function checkUserName(str) {
var pattern = /^[A-Za-z]\w{2,9}$/;
return pattern.test(str);
}The function returns true if the given username matches the following Criteria:The username must be at least 3 characters long.The username must be at most 10 characters long.The username must start with an English letter, whether it is alowercase or uppercase.Only English letters (a-z and A-Z), numbers and underscores are allowed.
Here, regular expressions (regex) are used to match the input string to the specified formats for a valid date and username, returning true if the input matches or false otherwise.

User Willwrighteng
by
8.7k points