prevent blank form submission - javascript

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.

Related

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 recheck required input fields in JavaScript/HTML5

I'm trying to stay away from JQuery for this one (nothing against JQuery, I just don't want to load a huge library into this project for something small like this).
I'm curious how I might tell HTML5 to recheck all the required input fields in a given form. For example, I have this form (albeit slightly more complicated but you get the point):
<form action="here" onsubmit="check()">
<input required name="something">
<input type="submit">
</form>
If I don't have anything in that required field, HTML5 shows a popup error, something to the effect of "Please fill in this required field". What is stopping the user from putting in a single space, or some nonsense character like % or >? I'd like to partially validate this client-side (in addition to server side) so it isn't particularly inconvenient when the page redirects to the form submission page and then shows the error, and then goes back to the form, prompting the user to enter everything over again.
Assuming in my onsubmit function check I've removed all whitespace and/or nonsense characters from the ends of the string, how can that function then tell HTML5 to recheck the form to see if the required fields are still not empty?
Instead of onsubmit="check()" use addEventListener.
Now you can do everything with input data.
document.getElementById("submit").addEventListener("click", function(event){
var something = document.getElementById("something").value;
document.getElementById("something").value = something.replace(/[^A-Z0-9]/ig, "");
});
<form action="here">
<input required name="something" id="something">
<input type="submit" id="submit">
</form>
try to use regexp pattern (e.g. exclude white chars: [^\s]*, allow only letters [A-Za-z]*, ...)
<form action="here" onsubmit="check()">
<input required pattern="[^\s]*" name="something" >
<input type="submit">
</form>

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>

Submit form via AJAX but keep client side validation

In my HTML code I have required fields and regular expression pattern checking using HTML5 attributes. I want to submit my data to my server via AJAX but I have to use e.preventDefault();
Using that, disables all the HTML5 attributes like "required" and "type=email" and the built in HTML5 client side check. Basically the user can just submit an empty form.
Is there a way to make HTML5 first check if the attributes i specified are met, then e.preventDefault from submitting so i can manually submit via AJAX?
$("input[type='submit']#input_submit").click(
function(e) {
//Prevents form from submitting right away:
e.preventDefault();
// Allows or keeps halting form submission process; returns true or false.
validationForm();
});
function validationForm() {
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="lastname">
<p>Last Name</p>
<input type="text" name="lastname" placeholder="Last Name" pattern="[a-zA-Z]+" title="Letters Only" required></input>
</section>
<input id="input_submit" type="submit" value="submit">
If you instead prevent the form submit from happening (instead of the button click), you will get the behaviour you want.
$("form#your_form").on("submit", function(e) {
e.preventDefault();
alert();
});
https://jsfiddle.net/4o8nnkjy/
So in the above example, the alert only happens if the form is valid.
You can change the submit for a button instead.
<input id="button" type="button">
Then, when the user clicks button
$('#button').click(function(){validationForm(input1, input2, etc);});
So, what have to do validationForm function? All you want to do with validations.
function validationForm(input1, input2, input3){
//Make all your validations
//Then, if all is correct, send the data via AJAX
}

Check $_POST data with jquery before submitting the form

I have a form that sends the store the First Name of the user in a database. I was checking the information send by the user using regex in php.
To make my project more interactive, I decided to validate the information jQuery before sending it to PHP.
My Project looks like this:
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
$(document).ready(function() {
$("form").submit(function (e) {
var firstname = $(this).find('input[name="firstname"]').val();
var regex = /^[A-Za-z0-9 \-']+$/;//Only numbers, Letters, dashes, apostrophes and spaces are accepted
if(regex.test(firstname)){
alert('Valid Name.');
}else{
alert('Invalid Name.');
e.PreventDefault();
}
});
});
</script>
Now I have 2 questions:
Is it really need to check the First Name in PHP again before storing the data in the database ? (To improve security)
How can I submit the form right after the alert('Valid Name.'); ?
Thanks for providing your help.
First of all have in mind that the validation of users input is implementing at the server side of an application only!!! You can not validate input data at client side with JS because it can be passed very easy(either by disabling javascript or by using tools like Curl).
However you can increase user experience like validate an input before submitting the form or inform the user that forgot to fill in an input.
To inform the user about a not fill in input you can just use the new html 5 attribute required like above
Username: <input type="text" name="usrname" required>
the required attribute will not let the user submit the form unless he had filled the associated input.
Also you can use the maxlength attribute to address a use case like "A password must have X max letters.
Password: <input type="password" name="pass" maxlength="8" size="8"><br>
How to validate input at server side
There are many techniques for this and you can find all of them here at Stackoverflow. Ι will refer the top voted post How can I prevent SQL injection in PHP? which answer exactly your question.
Just two bullets that compact the above post that i suggest you read otherwise
Always escape your data
Use mysqli instead of mysql
How can I submit the form right after the alert('Valid Name.'); ?
this is very easy just use this code
<form action="action_page.php" method="post">
<div>
<label>First Name</label>
<input name="firstname" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
the above code will "send" user's input for process at action_page.php using POST method, where you can read using $_POST supergloba table like $firstname = $_POST['fistsname'] etc.
TRY This
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js" ></script>
<script type="text/javascript" src="jquery-2.2.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js" type="text/javascript"></script>
<body>
<form >
<div>
<label>First Name</label>
<input name="firstname" id="first_name" type="text">
</div>
<div>
<input type="submit">
</div>
</form>
</body>
</html>
<script>
jQuery.validator.addMethod("firstName",function(value,element,param)
{
if(this.optional(element))
{//This is not a 'required' element and the input is empty
return true;
}
if(/^[A-Za-z0-9 \-']+$/.test(value))
{
return true;
}
return false;
},"Please enter a valid First Name");
$(function()
{
$('#myform').validate(
{
rules:
{
first_name:{ required:true, firstName:true }
}
});
});
</script>
Firstly you should ALWAYS validate server side for form submission, especially if you are passing those value along to a DB - SQL injection, the struggle is real.
As for the form submission flow you can...
return true
... after the valid name alert and the form to submit as it normally would.
Since you already have bound to that submit event, It would be even better for the user if you submitted the form via ajax, and providing feedback if the server validation fails. Thus the user never leaves the page and you are able to handle both client and server validation.
Take a look at ParsleyJS - http://parsleyjs.org/ - w00t!

Categories