Client-side JavaScript field validation - javascript

I have a particular scenario that I need a bit of help with in terms of client-side validation.
I have some input fields that are required (not HTML required) but they are identified as required using a class called "requiredInput" and is evaluated on server-side when the user clicks on the submit button.
I, however, would like to validate the input fields client-side when the user moves away from that field and disable submit till all the required fields are filled in.
How do I go about this scenario in order to handle this client-side completely rather than waiting for the server-side submit to perform the validation?
<input type="text" name="lastName" id="lastName" class="requiredInput" tabindex="3">
Note: I don't want to perform the validation on submit, I would like to validate onblur and disable submit till all the required fields are filled in.

You have bunch of JS validation packages that you can find accros the internet.
For now I think one of the best is ParsleyJS. You can use few build-in (and some extra) validators that work perfectly on client side. Ypou can design your own once. There is also possibility to validate field remotly which is also fine if you don't want to send whole the form to the server.

If you wan't a pure js solution and want full control of what exactly is valid you might want to do something like this:
Create a validateInput() function that gets all the input fields, checks if they have content (and whatever other checks you might want to perform) and proceed with enabling the submit button if everything is as expected. Attach that function to the onblur event of each input field.
function validateInput(){
let validInput = true;
let field1Content = document.getElementById('field1').value;
let field2Content = document.getElementById('field2').value;
if(field1Content.length === 0 || field2Content === 0)
validInput = false;
if(validInput)
//enable submit button
}

You can Easly do this if you have Jquery, try below
<input type="text" name="lastName" id="txtbox1" class="requiredInput clsValidate" tabindex="3">
<input type="text" name="lastName" id="txtbox2" class="requiredInput clsValidate" tabindex="3">
<input type="text" name="lastName" id="txtbox3" class="requiredInput clsValidate" tabindex="3">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
ValidateInput();
});
$(document).on('change', 'input.clsValidate[type=text]', function () {
ValidateInput();
});
function ValidateInput() {
var cnt = 0;
$('input.clsValidate[type=text]').each(function (i, obj) {
if ($(this).val().trim().length <= 0) {
cnt++;
}
if (cnt > 0) {
$('#btnsubmit').attr('disabled', 'disabled')
} else {
$('#btnsubmit').removeAttr('disabled');
}
});
}
</script>

Related

prevent blank form submission

If I want to prevent my form to be submitted if the fields are blank and highlight the blank fields.The code I have so far works if I try to submit when it is blank but doesnt submit if the fields are filled. I cannot seem to figure out what I am doing wrong. Please help
JavaScript code:
function CheckFields(){
if((document.getElementById('title').value=="") || (document.getElementById("textfield").value=="")){
const element = document.querySelector('form');
element.addEventListener('submit',event =>{
event.preventDefault();
alert("Fill the form to be submitted");
document.getElementById("title").style.backgroundColor=red;
document.getElementById("title").style.backgroundColor=red;
});
}
HTML:
<input name="post" type="submit" value="Post" onclick="CheckFields();">
Re-posted from: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation for the purposes of having the a static answer to this question, as the webpage may change
Using built-in form validation
One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap:
required: Specifies whether a form field needs to be filled in before the form can be submitted.
minlength and maxlength: Specifies the minimum and maximum length of textual data (strings)
min and max: Specifies the minimum and maximum values of numerical input types
type: Specifies whether the data needs to be a number, an email address, or some other specific preset type.
pattern: Specifies a regular expression that defines a pattern the entered data needs to follow.
In general that is a wrong way to validate fields, but anyhow your error is the order of the condition and form submit event. So it should be like this:
var myForm = document.querySelector('form');
var myTitle = document.getElementById('title');
var myTextfield = document.getElementById('textfield');
myForm.addEventListener('submit', event=>{
if(myTitle.value=="" || myTextfield.value==""){
alert("Fill the form to be submitted");
myTitle.style.backgroundColor=red;
myTextfield.style.backgroundColor=red;
return false;
} else {
return true;
};
});
You can add required to input fields for client-side validation. For more advanced validation, you may want to add server-side validation via a model.
See required in action:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="" required><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
You can validate a form in many ways. In Html 5 form you can add required for client side validation. You can also validate form from server side. And you can also use ajax for realtime form validation. Use focus on the field.. to highlight a field that is not filled.

Need Javascript for Specific Response in Contact Form (text must equal "yes")

I currently have a contact form that requires a user to type 'yes' to an agreement. I have knowledge of HTML and CSS, but do not know the possible Javascript code to require the user to enter 'yes' in the text box and to prevent the message from going through if they were to enter 'no' or any other response other than 'yes'. Any assistance would be greatly appreciated. Thank you!
You can use pattern attribute and the form will take care of the validation
<form>
<label for="confirm">Type yes</label>
<input type="text" id="confirm" name="confirm" placeholder="yes" pattern="^yes$" required>
<input type="submit" />
</form>
Simple JavaScript code will look something like
Will run when user tries to submit form
document.getElementByTagName("form").addEventListener("submit", function(event){
//get your input by id:
let input_validate = document.getElementById("your input id");
if(input_validate.value.toUpperCase() !== "YES"){
event.preventDefault();
alert('Please write yes in the input');
return false;
}
});
Hard to give you what you're looking for without more context/your HTML and how you want to handle an input you don't want (error message, prevent form submit, redirect to new page, all of the above). This could go in a function called onchange of the input, or within a function called during form submit.
var response = document.getElementById('[your_inputs_id]').value;
if(response == "yes"){
//do things, or submit, or do nothing
return true;
}
else{
//display error message, don't submit, etc.
return false;
}

HTML5 validation on existing values in an input box

I have a form that I am trying to validate using HTML 5 (and jQuery).
The form has initial values that are loaded in from a database. The users can edit the data and then submit the form. I have an input box with maxlength set to 6 but sometimes the value pulled from the DB has more than 6 characters in it. If the user doesn't do anything and just clicks submit then I want an HTML 5 validation warning. But the form just submits without a warning
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
I have tried adding a pattern {0,6} but this doesn't make any difference.
I don't want the form to remove characters automatically, the user must do this.
I tried using jQuery validate, but I don't think I am doing it correctly:
$(window).on("load", function() {
const $reading01 = document.querySelector('#reading01');
$reading01.validate();
}
If you normalise the <button> (ie. give it type="button" rather than type="submit") you can take advantage of the HTML5 Constraint API for Form Validation.
The HTML5 Constraint API enables you to define your own validation constraints.
Once the form validates, you can use submit() to submit the form.
Working Example:
const checkValuesForm = document.getElementById('checkValues');
checkValuesFormSubmitButton = checkValuesForm.querySelector('[data-type="submit"]');
const checkValues = (formSubmitted = false) => {
const reading01 = document.getElementById('reading01');
if (reading01.value.length > 6) {
reading01.setCustomValidity('This number cannot be more than 6 digits long');
reading01.reportValidity();
}
else {
reading01.setCustomValidity('');
if (formSubmitted === true) {
checkValuesForm.submit();
}
}
}
checkValuesFormSubmitButton.addEventListener('click', () => checkValues(true), false);
reading01.addEventListener('keyup', checkValues, false);
window.addEventListener('load', checkValues, false);
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" />
<button class="btn btn-primary" type="button" data-type="submit">Update</button>
</form>
Further Reading
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation
https://www.sitepoint.com/using-the-html5-constraint-api-for-form-validation/
you just need to display warning or prevent going further , in that case you can do your own validation by getting id and check it is empty or not.
Like Rounin says Je sus Monica said, using setCustomValidity is the cleanest way to send a message to inform of an error on a input. Still, since you are using a submit button, you can listen to your form's submit event and validate it before send the request. Also, you can use the Document.forms read only property, which returns a collection of HTMLFormElement. I like how it looks codewise, because it is very easy to understand that you are working with a form.
const form = document.forms['checkValues'];
form.addEventListener('submit', (e) => {
e.preventDefault();
const validatedInput = form.elements['reading01'];
if (validatedInput.value.length > 6) {
validatedInput.setCustomValidity("The input value cannot be longer than 6.");
return;
}
form.submit();
});
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
One more thing, and this is just a personal taste, when naming variables, I normally add the $ symbol for jQuery elements. So if by chance I am using a jQuery library, I can identify which variable holds a plain javascript element and which a jQuery element.

How to modify HTML5 form data before validation?

I am trying to reuse HTML5 validation required in simple serach form (so one input). It's exactly what I need (validation message in browser's language, styling, not allowing to progress, etc.). What I missing is trimming input string so not allowing user to submit just whitespaces.
I made research already and onsubmit event seems to be too late triggered to modify anything. I can't also make any change of actual inputs, so those has to remain intact during whole process (like with classic validation).
Is there any way to solve it with vanilla HTML5 without using libs like jQuery?
Edit: Using pattern attribute is not a solution here because it has different error message than this field cannot be empty.
You could try something along the lines of
<form method = "post">
<input type = "text" required pattern=".*[^ ].*" oninvalid="setCustomValidity('Please fill out this field')"
onchange="try{setCustomValidity('')}catch(e){}"/>
<input type = "submit" />
</form>
Otherwise if you really, really need to use only the required attribute you something like this would work for you
<form method = "post">
<input type = "text" required oninput = "if(this.value.trim() == '') { this.value = '' }"/>
<input type = "submit" />
</form>
You can use onsubmit, You just need to return false if it doesn't validate
<form onsubmit="return check()">
Enter name: <input type="text" id="myinput">
<input type="submit">
</form>
<script>
function check(){
if(document.getElementById("myinput").value.trim().length ==0){
return false;
}
return true;
}
</script>

Multi Scenario Form Action (Background, Multiple Actions, Timer)

I have tried using methods that may work for one scenario or another in AJAX, Javascript, JQuery and PHP, but I have not found a way to achieve the correct results for my scenarios.
I have a search box text input field as :
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
There are three scenarios in which different actions need to occur:
On page load, send the input to search-api.php as POST every 5 seconds in the background, and get results back from the action and set the response equal to $url. (Must not only show response for first submit, but also for all changes in input when updated every 5 seconds).
When enter button is pressed, send the input as GET to https://externalaction.com/search in foreground.
When button <input class="button default" name="BtnX" type="submit" value="Search"> is pressed, send the input as GET to https://externalaction.com/search in foreground.
I know this is complicated but I have yet to find a solution that works for all three scenarios without interfering with each other, and no one online seems to have any information or questions quite like this situation.
Thank you to anyone who has any help, tips, or answers / code!
This doesn't seem too complicated, although I'm not sure why you'd want to send search queries every 5 seconds instead of on keypress? In any case it should just be using $.post() and setTimeout.
<form action="https://externalaction.com/search" method="get">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
<div id="results"></div>
<script>
$(function() {
search();
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
setTimeout(search, 5000);
}
</script>
If you're interested in using keypress instead of every 5 seconds, it would be something like this for the JS:
<script>
$(function() {
$('#field').on('keyup change', 'search');
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
}
</script>
Although in this case you don't need a named function, you could just make the search() function the keypress callback.
You also mentioned wanting to set the AJAX response to $url, however that looks like a PHP variable, so you wouldn't be able to modify that if it's in the page with the form unless you reloaded it. That's easy enough to do if you wanted to programmatically do a redirect, but would get pretty tricky and into weird loops. So it would be better to know what $url is being used for in the page, and then use JS to replace it with the value from the callback the same way I'm replacing the HTML of the results div in my current example.
The search form field will submit automatically on an 'enter' keypress as long as it has focus (i.e. after someone is finished typing in it and hits 'enter'), but if you want to send results whenever enter is pressed regardless of which input has focus this answer will help.
As an aside, typically you don't want to recursively keep searching with a timeout without some kind of end condition which clears the timeout, as in some cases it can lead to memory issues.
first of all you should search input is a form and need form tag even if it's only one input. lets consider it like this:
as you set set button type to submit. the 2 and 3 options would work.
<form id="search-form" action="https://externalaction.com/search" method="GET">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
second of all in case if in some situations (really rare) some browsers didn't work properly with type="submit" for enter button you should use jQuery like this one:
$(function() {
$("#search-form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#search-form button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
for autocomplete search you can use many exist libraries or write it yourself I recommend to read this article for an example:
http://ianlunn.co.uk/articles/ajax-search-suggest-wearehunted/
actually if you use a standard form element the only thing you are looking for is just a autocomplete search input which i believe users used to see result by typing each word instead every 5 second. but its up to you.
Edited according to your last comment:
if you have a single action for search you should at least use two different view.
to use autocomplete feature you should use ajax and if you want to have only one action or page just send an extra parameter and make a partial-view which echo result back in Json instead of a complete view which contains header and footer and ...
Function searchData() handle the AJAX request. setInterval(function(){searchData()}, 5000) section handle request search content every 5 second. If click on Enter key, then that request handle on keydown event, finally click function handle the request come through the search button.
search.php
<!--- Search field and button -->
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input type="button" name="search" id="search" value="Search"/>
<!--- Display result -->
<span id="res"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
// function used for AJAX call
function searchData(){
var txt = $("#field").val();
$.get("searchData.php", {search: txt}, function(result){
$("#res").html(result);
});
}
// search every 5 second
setInterval(function(){searchData()}, 5000);
// if press enter button search
$('#field').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
searchData();
}
});
// if search button press
$("#search").click(function(){
searchData();
});
});
</script>
searchData.php - Page used to handle the request
<?php
// testing purpose
echo $_GET['search'];
?>

Categories