Reputation: 177
I am wondering if there is a certain way to validate a HTML form upon an error being returned. For instance, I have a form where the user can input their string which is then used to query data to do with that string. Ideally, I would like a way for the form to be validated if the user inputs the string wrong i.e. with capitals or spelling mistakes. But I think that could only be realized once the system has tried to get the data responding to that string.
I hope Stack Overflow is an appropriate place to ask this.. after looking around in the hopes to find an answer to my question I can't seem to find a valid way to approach this.
Is there a way in HTML to validate the form in the event that an error is returned? Apologies if this is obvious, I am quite new to the concept of validating forms.
Thanks in advance.
Upvotes: 0
Views: 45
Reputation: 303
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
What you're looking for is actually new technology AFAIK. Once upon a time, you needed to use a scripting language, i.e. JavaScript to do something like this. But it turns out you can actually add regular expressions, ranges of values, ranges of lengths, and more straight into your HTML for each input, and the browser will do all the work for you.
An example from the MDN source above
<form>
<label for="choose">Would you prefer a banana or a cherry?</label>
<input id="choose" name="i_like" required pattern="banana|cherry" />
<button>Submit</button>
</form>
Where your input is required, and it must match exactly either banana or cherry. The browser will handle the process of informing the user their input hasn't worked and prevent you from submitting to the server.
Here's a live example I made out of the above code block: https://codepen.io/anon/pen/zjdrbV
Sometimes, though, you might need to validate an input that requires more than what the HTML validation can provide.
In that case, you'll just have to write a little JavaScript. Here's a good example of that: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation under section Limiting the size of a file before its upload
. There's tons of resources on that sort of thing, and most likely you'll be able to find plenty of help for virtually any input you need to validate.
Upvotes: 2