I have a input field, which will record the response of the end-user. Say the label of it is Linkedin URL. The user who has to enter the linkedin URL could enter some other input(facebook.com/satyaram2k14), which is not invalid. So how can one check, if the url entered contains string 'linkedin.com' along with other text. Final url should be 'linkedin.com/satyaram2k14'. How can I check for this pattern at front-end.
2 Answers
There are several approaches you can take:
- Rely on the HTML5 form validation via
requiredandpatternattributes - Validate the input value via JavaScript on form validation
- Optionally provide a visual hint on the (in)valid state of the field content
HTML5 validation works in any modern browser and integrates into the browser UI (including localisation of error messages). But it's not as flexible and the helpfulness of the error message given when the pattern does not match varies from browser to browser.
In any case, you should always validate user input on the server side as well, because any client validation can be circumvented.
Here are some code examples of all three approaches. They all use the RegEx pattern ^https?://(www\.)?linkedin\.com, so they'll allow http or https protocol and urls with or without "www.".
var form = document.getElementById('form');
var field = document.getElementById('url');
var fieldstatus = document.getElementById('fieldstatus');
var regExPattern = new RegExp('^https?://(www\.)?linkedin\.com', 'i');
// validation on form submit
form.addEventListener('submit', function(ev) {
if (!regExPattern.test(field.value)) {
ev.preventDefault();
alert('The input value does not match the pattern!');
}
});
// validation on input
field.addEventListener('input', function() {
if (!regExPattern.test(field.value)) {
fieldstatus.innerHTML = 'invalid';
} else {
fieldstatus.innerHTML = 'valid';
}
});
<h1>HTML5 validation pattern</h1>
<form>
<input type="text" pattern="^https?://(www\.)?linkedin\.com" required /><br>
<input type="submit" />
</form>
<h1>Custom JavaScript validation</h1>
<form id="form">
<input type="text" id="url" /> <span id="fieldstatus">invalid</span><br>
<input type="submit" />
</form>
Comments
One quick way of doing this is by using the pattern attribute of input, like so:
<input type='text' pattern='^linkedin\.com/'>
^linkedin\.com/ being a regular expression that matches all strings that start with linkedin.com/.
Using this attribute, the browser by itself will only accept such strings.