In: Computer Science
So I'm writing a function in javaScript that will take a user full name in one text box. "first" space "last name" But if the user does not enter the space then there should be an error. So I'm looking for a way to validate this so the user needs to enter the space.
Since we have to validate a pattern, we can use Regular Expressions. We can assign a pattern in a variable and compare it with the user's input to validate.
The following code explained:
1. Store the regular expression in a variable "regularExpression"
The regular expression is: ^[a-zA-Z]+ [a-zA-Z]+$
Note that the first [a-zA-Z] is for the first name and the second is for last name.
a-z : It is for lowercase letters
A-Z : It is for uppercase letters
Note: There is a space after the + operator which denotes a space between the two names.
2. The user's input will be stored in variable "name"
3. In the if statement, use the test( ) method to match the input string and the regular expression. If the condition doesn't satisfy , print an alert message and return false.
4. In the else block, which means that the pattern has matched and there is a space between both the names.So, alert the message as "Entered name is valid" and return true.
Code:
function validate(){
var regularExpression = /^[a-zA-Z]+ [a-zA-Z]+$/;
var name = document.getElementById('name').value;
if(!regularExpression.test(name)){
alert('Error! Enter your full name - First Name and Last Name');
document.getElementById('name').focus();
return false;
}
else{
alert('Entered name is valid');
return true;
}
}
This is the entire code:
<html>
<head>
<title>Example</title>
</head>
<body>
<p>Full Name: <input id="name" value=""></p>
<input type="button" onclick="validate();" value="Validate Name">
<script>
function validate(){
var regularExpression = /^[a-zA-Z]+ [a-zA-Z]+$/;
var name = document.getElementById('name').value;
if(!regularExpression.test(name)){
alert('Please enter your full name (first & last name).');
document.getElementById('name').focus();
return false;
}else{
alert('Valid name given.');
return true;
}
}
</script>
</body>
</script>