HTML5 validation executes before custom validation - javascript

I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>

This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>

Related

Hide/locking a <form> button until form is completely filled with validation

I make my JSON script with a form and a button, but when I demo it on someone, they can press the submit button whenever they like. Here is my code:
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br>
</form>
All I need now is validation and how to lock or hide the button. I tried using <script> with function and getElementById but I simply do not know how to lock it. Here is the message that will be inputted when it is locked and the form isn't completed:
You have not finished the information input for the survey. Please
input "Your First Name" and "Your Last Name" to enter the survey.
When they finish, I will input a loading icon until fully loaded.
Code Language(s)
I use fiddles to make my code, so I use:
HTML
JSON
Pinch of jQuery (loading icon)
Answer Expectations
In my answers, I need:
Recommended Code Language
Code for note purposes
Crossed out attributes
Attributes before coding explanations
EDIT: I just noticed that I can use the disabled boolean attribute here, so all I need is validation to disable the boolean attribute so they can press the button.
Hello I recommend JavaScript but it is not secure at all. However its the most effective in this case. Here is the code: (Note that i changed the html too)
<form action="action_page.php" method="get" >
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="inputEntries()"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" onkeyup="inputEntries()"><br><br>
<button type="submit" name="submit" id="submit_btn" disabled="true">submit</button>
</form>
<script>
var fname_var = document.getElementById("fname");
var lname_var = document.getElementById("lname");
var submit_btn_var = document.getElementById("submit_btn");
function inputEntries(){
if(lname_var.value != "" && fname_var.value != "")
submit_btn_var.disabled = false;
else
submit_btn_var.disabled = true;
}
</script>
What it does is that if both input fields are empty the button is not clickable but if both are it can be clicked. hope it helped!
You can use either pure javascript or jQuery to validate.
In the below code you would see we are first binding a change event to the input field and getting its values. If both values are present, the disabled attribute of the submit button is removed. Else the opposite.
<p id="msg">You have not finished the information input for the survey. Please input "*Your First Name*" and "*Your
Last Name*" to enter the survey.</p>
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br><br>
<button type="submit" id="btn-submit">Submit</button>
</form>
$(document).ready(function(){
('#btn-submit').prop('disabled', true);
$("input[type=text]").change(function(){
if ($('#fname').val() && $('#lname').val()) {
$('#btn-submit').prop('disabled', false);
$('#msg').hide();
} else {
$('#btn-submit').prop('disabled', true);
$('#msg').show();
}
});
});
Stackblitz - https://stackblitz.com/edit/jquery-kgzhuo?file=index.html

Adding *Required next to an empty input

So I was wondering how I could implement required fields into my code. I tried just using required="" in the <input> tag, however, this doesn't work across all browsers. I was wondering if someone could explain how to add "* Required" next to the input if the user tries to submit and the field is empty.
Here's my form code:
contact.html
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
formvalidate.js
function validateForm()
{
var a=document.forms["Form"]["email"].value;
var b=document.forms["Form"]["subject"].value;
var c=document.forms["Form"]["message"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="")
{
alert("Please Fill All Required Field");
return false;
}
}
var input = document.getElementById('a');
if(input.value.length == 0)
input.value = "Anonymous";
First of all this is wrong:
if (a==null || a=="",b==null || b=="",c==null || c=="")
Presumably you lifted that from here and as noted in the comments, it doesn't do what it claims and will only check the last field.
To add the message you can modify your validation function to check each field and insert some text. The snippet below should give you a basic idea - and since you're new to javascript I've commented each bit with an explanation. Hope this helps:
function validateForm() {
// start fresh, remove all existing warnings
var warnings = document.getElementsByClassName('warning');
while (warnings[0]) {
warnings[0].parentNode.removeChild(warnings[0]);
}
// form is considered valid until we find something wrong
var has_empty_field = false;
// an array of required fields we want to check
var fields = ['email', 'subject', 'message'];
var c = fields.length;
// iterate over each field
for (var i = 0; i < c; i++) {
// check if field value is an empty string
if (document.forms["Form"][fields[i]].value == '') {
// create a div with a 'warning' message and insert it after the field
var inputField = document.forms["Form"][fields[i]];
var newNode = document.createElement('div');
newNode.style = "color:red; margin-bottom: 2px";
newNode.className = "warning";
newNode.innerHTML = fields[i] + ' is required!';
inputField.parentNode.insertBefore(newNode, inputField.nextSibling);
// form is now invalid
has_empty_field = true;
}
}
// do the alert since form is invalid - you might be able to skip this now
if (has_empty_field) {
alert("Please Fill All Required Field");
return false;
}
}
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
And of course you always need server side validation as well! Client side is really only to help get a snappy UIX and can be easily fail or becircumvented by any user who has a mind to do so. Any data you send to the server needs to be checked over and if something's wrong an error should be returned and handled properly on the form page.
The input field becomes a required field when you specify inside the field that it is a required field. Just placing an asterisk * or placing the word required next to it will not make it required.
Here is how to make an input field required in HTML5
Username *: <input type="text" name="usrname" required>
It is the attribute "required" of the element itself that makes it required.
Secondly.. when using the HTML5 validation you will not need javascript validation because the form will not pass the html5 validation. Having both client-side and server-side is important.

How to check if textbox is empty and display a popup message if it is using jquery?

I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

I am doing a web application using javascript and html that has a form containing a text field, button. When I enter a number in that text field and submit by clicking on that button, text areas are generated dynamically. Once my form is submitted some text areas are created but if I am not satisfied with existing text areas then again I enter some value with out refreshing page. But the text field value entered previously prevails showing the new text areas below the existing text areas on the page.
So, how do I clear the value with out refreshing the page.
<div>
<html>
<input type="text" name = "numquest" id ="numquest" value="" size="5" style="" disabled>
<input type="button" value="submit" onclick="getFields();">
</div>
</html>
<javascript>
var num_q=document.getElementById('numquest').value;
//code for dynamic creation
</javascript>
try this:
Using jQuery:
You can reset the entire form with:
$("#myform")[0].reset();
Or just the specific field with:
$('#form-id').children('input').val('')
Using JavaScript Without jQuery
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
function submitForm() {
// Get the first form with the name
// Hopefully there is only one, but there are more, select the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit
frm.reset(); // Reset
return false; // Prevent page refresh
}
You can set the value of the element to blank
document.getElementById('elementId').value='';
Assign empty value:
document.getElementById('numquest').value=null;
or, if want to clear all form fields. Just call form reset method as:
document.forms['form_name'].reset()
you can just do as you get that elements value
document.getElementById('numquest').value='';
<form>
<input type="text" placeholder="user-name" /><br>
<input type=submit value="submit" id="submit" /> <br>
</form>
<script>
$(window).load(function() {
$('form').children('input:not(#submit)').val('')
}
</script>
You can use this script where every you want.
It will clear all the fields.
let inputs = document.querySelectorAll("input");
inputs.forEach((input) => (input.value = ""));
HTML
<form id="some_form">
<!-- some form elements -->
</form>
and jquery
$("#some_form").reset();
I believe it's better to use
$('#form-id').find('input').val('');
instead of
$('#form-id').children('input').val('');
incase you have checkboxes in your form use this to rest it:
$('#form-id').find('input:checkbox').removeAttr('checked');
.val() or .value is IMHO the best solution because it's useful with Ajax. And .reset() only works after page reload and APIs using Ajax never refresh pages unless it's triggered by a different script.
I had that issue and I solved by doing this:
.done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
I added this code after my script as I used jQuery. Try same)
<script type="text/JavaScript">
$(document).ready(function() {
$("#feedback").submit(function(event) {
event.preventDefault();
$.ajax({
url: "feedback_lib.php",
type: "post",
data: $("#feedback").serialize()
}).done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
});
});
</script>
<form id="feedback" action="" name="feedback" method="post">
<input id="name" name="name" placeholder="name" />
<br />
<input id="surname" name="surname" placeholder="surname" />
<br />
<input id="enquiry" name="enquiry" placeholder="enquiry" />
<br />
<input id="organisation" name="organisation" placeholder="organisation" />
<br />
<input id="email" name="email" placeholder="email" />
<br />
<textarea id="message" name="message" rows="7" cols="40" placeholder="сообщение"></textarea>
<br />
<button id="send" name="send">send</button>
</form>
You can assign to the onsubmit property:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit

Why my form doesn't validate correctly?

I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.
HTML:
<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">
<div id="errors"></div>
<label for="author">Name:</label><br/><br/>
<input type="text" name="author" id="message" /><br/><br/>
<label for="author">Message:</label><br/><br/>
<textarea name="message" id="message"></textarea><br/><br/>
<input type="submit" class="button" value="Send Message"/>
</form>
Javascript:
<script type="text/javascript">
function error(message){
return "<p class=\"error\">"+message+"</p>";
}
function validate(){
var form = document.getElementById("contactForm");
var author = document.getElementById("author");
var message = document.getElementById("messsage");
var errors = document.getElementById("errors");
alert(author.value);
if(message.value == '' || author.value == ''){
errors.innerHTML = error("Please fill in all fields.");
return false;
} else {
return true;
}
}
</script>
id=author on your first input element.
Also check out jQuery it will save you time in the long run
You have two elements with the id message and none with author.
The Markup Validator would have picked this up for you.
var message = document.getElementById("messsage");
message has an extra "s".
<input type="text" name="author" id="message" />
You need to change "message" to "author"
This is wrong:
<input type="text" name="author" id="message" />
Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.
Also both your label tags have for="author"; the second one is wrong.
I guess your problem here is too much copy+paste. ;)

Categories