I've created a simple form where I want the 'first name' field to only allow letters (lowercase and uppercase) and spaces. I've used the following pattern:
pattern="[a-zA-Z ]*"
It seems to work, but I also tried pattern="[a-zA-Z ]"
but this failed.
Is the pattern="[a-zA-Z ]*"
code the correct regular expression for this requirement, or will it allow some other characters? If so, why do you need the asterisk? I've seen other similar regular expressions have no asterisk, and it's making me believe that there'll be some characters that can be entered other than my requirements.
I can't actually find somewhere that explains regular expressions, like a blog article, another stack overflow post, video, or anything that accurately teaches regular expressions and would be keen to read if anyone has written anything about this. Thanks for any help here
Codepen URL: https://codepen.io/anon/pen/rgvyjq
function showEmailError() {
let emailError = $('#email-error');
emailError.fadeIn('slow');
emailError.text('Please enter a valid email address');
setTimeout(() => emailError.fadeOut('slow'), 3000);
}
form {
background: #f0f0f0;
padding: 25px;
border-radius: 5px;
display: flex;
flex-flow: row wrap;
}
form input, form label, form textarea { flex-basis: 100% }
form label { padding-bottom: 5px }
form input { padding: 5px }
form input:not(:last-of-type) , form textarea { margin-bottom: 15px }
form textarea { min-height: 50px }
form button {
padding: 10px 15px;
margin-top: 20px;
font-size: 0.8em;
border: 1px solid #ccc;
}
#email-error {
background: #FB5835;
flex-basis: 100%;
padding: 10px;
display: none;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<form method="post">
<label for="forename">* First Name:</label>
<input type="text" id="forename" name="first-name" required="required" minlength="2" maxlength="20" pattern="[a-zA-Z ]*" oninvalid="setCustomValidity('Invalid Forename')" oninput="setCustomValidity('')">
<label for="surname">Last Name:</label>
<input type="text" id="surname" name="last-name">
<label for="address">Addess:</label>
<textarea type="text" id="address" name="address"></textarea>
<label for="country">Country:</label>
<input type="text" id="country" name="country">
<label for="postcode">Postcode:</label>
<input type="text" id="postcode" name="postcode">
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone">
<label for="email">* Email:</label>
<span id="email-error">Error</span>
<input type="text" id="email" name="email" required="required" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" oninvalid="showEmailError()">
<button type="submit">Submit</button>
</form>