How to validate an input type=“text” element to only accept certain content?

I have a text input field:

<input type="text" name="email" size="25" placeholder="Email Address" required/>

Is there a way to format the input field to only allow certain text to be valid?

For example: In that particular text field, the user must input an email address which ends in “@hotmail.co.uk”. Any other email domains such as “@yahoo.com” will not be valid and therefore will show an error when clicking submit (Will not register the user).


solution

You can use the HTML5 pattern attribute to validate whether the string ends with @hotmail.co.uk.

In this case you can use the following regular expression:

^.*@hotmail\.co\.uk$
<form>
<input type="text" name="email" pattern="^.*@hotmail\.co\.uk$" size="25" placeholder="Email Address" required/>
<input type="submit" />
</form>

Alternatively, you could also just attach an input event listener to the element and check manually. This is just a basic example, feel free to customize to your needs. I would still suggest validating that the value is a valid email address by using the regex from this question.

$('input[name="email"]').on('input', function(e) {
var isValid = this.value.match(/^.*@hotmail\.co\.uk$/) !== null;
  $(this).toggleClass('isValid', isValid);
});
.isValid {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="email" size="25" placeholder="Email Address" required/>
<input type="submit" />
</form>