Validation field setCustomValidity() method - javascript

I have to do the validation of the input text field.
I would like Js to show an error message through the setCustomValidity() method.
Is it possible?
function checkName() {
var x = document.formUser;
var input = x.name.value;
if (input.length < 3) {
input.setCustomValidity('This field is invalidate');
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return validateForm();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="validateForm();">
</form>

You need to call reportValidity() on the input after setting the custom validity message.
Additionally you must call the reportValidity method on the same element or nothing will happen.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity#examples
function checkName() {
const inp = document.getElementById('name');
const val = inp.value;
if (val.length < 3) {
inp.setCustomValidity('This field is invalidate');
inp.reportValidity();
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return checkName();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="checkName();">
</form>

I would like to control more text input with javascript.
The setCustomValidity() method means that it will have to show an error message if input has less than three characters.
it doesn't always work.
Eg. If I put a string of one character in the first field and a string of four in the second field; it sends without showing the error. If I repeat the same test, it works.
Why?
window.onload = function() {
const field = document.getElementsByClassName("input-field");
for (let i = 0; i < field.length; i++) {
field[i].addEventListener('input', function() {
const val = field[i];
if (val.length < 3) {
field[i].setCustomValidity('Field is invalid');
}
})
}
}
<form name="formUser" id="formUser" action="#">
<div class="section">
<label for="fname">First name</label>
<input class="form-control input-field" type="text" id="fname" required>
<label for="lname">Last name</label>
<input class="form-control input-field" type="text" id="lname" required>
</div>
<input type="submit" class="btn btn-primary" value="Send">

You could add a <p class="error">...</p> inside your section div.
Hide it with css (display: none) and when you get an error in your validation add a class to that like "show" to show it (display: unset).

You can do custom form validation using Javascript like this.
Here I have just added a div with a warning and alert box. You can do whatever you want.
It will alert a warning if you will click on submit when fields were empty.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
let alertBox = document.getElementById("alert-box");
// Here instead of checking (x == " "), you can use your custom validations
if (x == "") {
alertBox.innerHTML = `<p>Form input are empty</p>`; // appends a div with warning
alert("Name must be filled out"); // alert box
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<div id="alert-box"> </div>
<form name="myForm" action="#" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

Related

How to show form validation errors in inputs NOT one by one in popups?

I have a very simple form here with 2 required inputs.
When you click submit button without filling them - there are popups saying that you should do it. The problem is that popups are showed one by one - for example, if both inputs arent filled, only the first input will have this popup. And when the first one is filled only then it goes to the second and vice versa.
Is there any way to show all the fields that are not filled/filled incorrect during the validation at the same moment? So the user sees immediately everything he/she has to fill?
I am quite new to this, so please help me find the solution in pure JS (if it is about JS).
Here is the code:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST">
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" required=""
oninvalid="setCustomValidity('Enter first name')" oninput="setCustomValidity('')"
placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" required=""
oninvalid="setCustomValidity('Enter last name')" oninput="setCustomValidity('')"
placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
The code you provided is using a built in function of JavaScript, setCustomValidity(). This most likely is the reason for the pop-up. Instead we can write a custom function to show a little paragraph/span with the text instead.
Here we have a HTML form, but with a call for the custom function validateFields(), when clicking the Submit button:
<form class="" action="your-post-page.html" method="post" id="my-form-id" name="my-form-name" onsubmit="return validateFields()" target="_blank" class="validate" novalidate="">
<input id="name_1" type="text">
<br><br>
<input id="name_2" type="text">
<br><br>
<input id="name_3" type="text">
<br><br>
<input type="submit" name="" value="SUBMIT FORM">
</form>
<p id="error_messages" style="background-color: red; color: white;"></p>
The JS that makes it happen:
(custom function that reacts to inputs being empty and lets the user know which fields need fixing, put code before the </html> tag in your html-page)
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["name_1", "name_2", "name_3"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["Name 1", "Name 2", "Name 3"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["my-form-id"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
Now lastly, here is your own code with this example:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST" onsubmit="return validateFields()" >
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
<!-- here I added a new box for the error messages in your code -->
<div class="">
<p id="error_messages" style="background-color: red; color: white;"></p>
</div>
</div>
</form>
</body>
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["first_name", "lastName"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["First name", "Last name"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["mainForm"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
</html>
That was with custom scripting to get a box that you can style and enhance yourself, in this case below the form. But if you are okay with some default (and perhaps not unified styling, due to browser differences) you can also just remove the JavaScript function you had in your original code, the setCustomValidity(''). That will leave you with a generic message using the already present attribute required="", which produces this:
To achive that behaviour, change your tags for each field to look like this instead:
<input id="first_name" name="first_name" type="text" value="" required="" placeholder="Enter first name">

AutoClear input field after submit with Js

Would like your help resolving this piece of code.
Trying to clear inputs after submit but not able to.
Can someone give me a hint??
Thank you so much.
<script>
var list = document;
function process(idTable)
{
var newRow = list.createElement('tr');
newRow.insertCell(0).innerHTML = list.getElementsByName('name')[0].value;
newRow.insertCell(1).innerHTML = list.getElementsByName('surname')[0].value;
newRow.insertCell(2).innerHTML = list.getElementsByName('email')[0].value;
list.getElementById(idTable).appendChild(newRow);
return false;
list.getElemntsByName('form')[0].value="";
}
</script>
<section>
<form name="form" method="post" id="myForm" onsubmit=" return process('myTable')" >
<p> <label>Name:</label> <input type="text" name="name" placeholder = "Your first name" required> </p>
<p> <label>Surname:</label> <input type="text" name="surname" placeholder = "Your last name" required> </p>
<p> <label>Email:</label> <input type="e-mail" name="email" placeholder = "xpto#example.com" required> </p>
<p> <input type="submit" value="Add"> <input type="reset" value="Reset"> </p>
</form>
</section>
Two points:
You exited the function before assign value to the form
Better use list.getElemntsByName('form')[0].reset();
So your code will be like this:
<script>
var list = document;
function process(idTable)
{
var newRow = list.createElement('tr');
newRow.insertCell(0).innerHTML = list.getElementsByName('name')[0].value;
newRow.insertCell(1).innerHTML = list.getElementsByName('surname')[0].value;
newRow.insertCell(2).innerHTML = list.getElementsByName('email')[0].value;
list.getElementById(idTable).appendChild(newRow);
list.getElemntsByName('form')[0].reset();
return false;
}
</script>
Why don't you use button tag for your 'submit' and 'reset', then in that use clientclick event, have reset function that clears the input tag.
Use $('#id of input element ').val(' ') inside process function . Also write this code above return false statement

Is there an event I can listent to that takes place after a form submit and after the form has been verified with HTML5?

I have this form:
<div id="account-form">
<form action="/Account/Login" id="login-form" class="form" method="post">
<div id="input-fields">
<div>
<input class="data-entry medium-margin" id="UserName" name="UserName" placeholder="Username (or guest)" required="required " size="25" type="text" value="">
</div>
<div>
<input class="data-entry medium-margin" id="Password" name="Password" placeholder="Password (or guest)" required="required " size="25" type="password">
</div>
<div>
<input class="data-entry inline-checkbox" id="RememberMe" name="RememberMe" type="checkbox" value="true"><input name="RememberMe" type="hidden" value="false">
<p style="margin-top: 0;">Remember me?</p>
</div>
</div>
<button class="data-entry medium" id="login" type="submit">Login</button>
<button class="data-entry medium" id="register" type="button" onclick="location.href='/Account/Register'">Register</button>
</form>
</div>
and this javascript that disables the inputs after the form submit.
<script type="text/javascript">
(function() {
document.getElementsByClassName('form')[0]
.addEventListener("submit", function () {
var inputs = document.getElementsByClassName("data-entry");
for (i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
})();
</script>
When I enter login data and then click submit the inputs are disabled and the submit verification fails saying that the input fields are not filled out.
Is there some way I can disable the input fields after HTML5 verification?
Just schedule a callback with a timeout of 0
.addEventListener("submit", function () {
setTimeout(function() {
var inputs = document.getElementsByClassName("data-entry");
for (i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
}, 0); });
This way the disabling code will be executed once the submit event processing has been completed. You will have however to re-enable the fields in case the verification fails otherwise the user will not be able to correct the problem.

jquery find input before button

I have a single form on the page and I have some jQuery to make sure that the inputs have been completed before the submit.
But now I need to have multiple similar forms repeated on the page and I need to change the jQuery to only check the two inputs in the form that the button was clicked and not check any other form on the page.
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
The jQuery that I have used previously to check on form using ID
// validate signup form on keyup and submit
jQuery('#submitDates').click(function () {
var found = false;
jQuery("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && jQuery(name).val()=='') {
alert ('Please choose your arrival and departure dates!')
found = true;
} ;
});
return !found;
});
.prev( [selector ] )
Returns: jQuery
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
This is quite short and will target any input displayed just before a button :
$("button").prev("input")
jsFiddled here
you can try like this:
CODE
jQuery('.submitDates').click(function () {
var found = false;
jQuery(this).siblings("input").each(function (i, name) {
// Check if field is empty or not
if (!found && jQuery(name).val() == '') {
alert('Please choose your arrival and departure dates!')
found = true;
};
});
return !found;
});
assuming your inputs are siblings for the button. Note I also changed button's id into class.
FIDDLE http://jsfiddle.net/FY9P9/
Closest and Find do it as well, wherever the input are for the button :
HTML:
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
JS:
$(".button").each(function () {
$(this).click(function () {
if (($(this).closest(".form").find(".toDate").val() == "") || ($(this).closest(".form").find(".fromDate").val() == "")) {
alert("Please fill in arrival and departure Date");
}
})
})
http://jsfiddle.net/GuqJF/1/

Stop Submit With Empty Input Values

Im Looking for a simple solution to stop a login form from submitting with empty input fields. The code for the form is below. I would like to use a simple Javascript soluiton if possible.
<form id="login" method="post" action="">
<input type="text" name="email" id="email" />
<input type="password" name="pwd" id="pwd" />
<button type="submit" id="submit">Login</button>
</form>
If possible I would also like to change the border of the empty field(s).
Thanks in advance.
Sample code with dummy checks:
<script type="text/javascript">
function checkForm(form) {
var mailCheck = checkMail(form.elements['email']),
pwdCheck = checkPwd(form.elements['pwd']);
return mailCheck && pwdCheck;
}
function checkMail(input) {
var check = input.value.indexOf('#') >= 0;
input.style.borderColor = check ? 'black' : 'red';
return check;
}
function checkPwd(input) {
var check = input.value.length >= 5;
input.style.borderColor = check ? 'black' : 'red';
return check;
}
</script>
<style type="text/css">
#login input {
border: 2px solid black;
}
</style>
<form id="login" method="post" action="" onsubmit="return checkForm(this)">
<input type="text" name="email" id="email" onkeyup="checkMail(this)"/>
<input type="password" name="pwd" id="pwd" onkeyup="checkPwd(this)"/>
<button type="submit" id="submit">Login</button>
</form>
Possible approach:
setting action to #
adding handler to the submit button or the onsubmit of the form
change the action of the form, if text fields are not empty
Edit: To make this even work for non-javascript users insert the #-action when page is loaded.
To keep it minimal I would just use:
<form id="login" method="post" action="" onSubmit="if (this.email.value == '' || this.pwd.value == '') {return false;}">
Granted - doesn't point out what's amiss to the user, but works a treat.

Categories