How to intercept HTML5 input validation with JavaScript? - javascript

<form ... onsubmit="return false">
<input type="text" name="location" ...>
<input type="url" ... required>
...
</form>
Now, if I enter a location and hit ENTER, the browser tells me that an URL is required which is not an expected or desired outcome. The ENTER should just be ignored.
Question
How can I prevent the browser from checking the required field after hitting ENTER in the "location" input field and only let the browser check the "url" field when submitting the form with JavaScript using form.submit()?

You need to stop the default behavior of enter button for your form elements.
Lets have an example:
HTML5 form as
<form id="form">
<input type="text" name="test1" id="test1" required/>
<input type="text" name="test2" id="test2" required/>
<input type="submit" value="Test"/>
</form>
Then apply below code
$(document).ready(function() {
$(form).find('input').on('keydown', function(e){
if(e.which == 13) // KEY.ENTER = 13
e.preventDefault();
});
});
Based on above scenario, here is the fiddle.

This is what I did now and what worked (using jQuery, where $form represents the ):
$form.find('input').on('keydown', function(e){
if(e.which == KEY.ENTER) // KEY.ENTER = 13
e.preventDefault();
});

You can use the novalidate attribute in your form element:
<form method="post" action="..." novalidate>...</form>

There is a specific method for handle a "submit".
Here's here!

Related

How can I prevent form submission if value is too short?

I want to prevent any form submission, if the input field is not at least 3 chars long. My button is disabled if length <= 3 but I cant prevent the submission on "Enter".
<form name="form" action="..." method="POST" id="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<input type="button" id="btnSubmit" value="Add" disabled>
</form>
</div>
<script>
const form = document.querySelector('#form');
const inputName = document.querySelector('#name');
const btnSubmit = document.querySelector('#btnSubmit');
inputName.addEventListener('input', function(event) {
btnSubmit.disabled = inputName.value.length < 3;
});
inputName.addEventListener('keypress', function (event){
if (event.keyCode === 13) {
event.preventDefault();
if (inputName.value.length >= 3) form.submit();
}
});
form.addEventListener('keypress', function (event){
event.preventDefault();
});
Set a minlength value for your input field
<input type="text" class="form-control" id="name" name="name" minlength="3" required>
The minlength attribute defines the minimum number of characters (as UTF-16 code units) the user can enter into an or . This must be an integer value 0 or higher.
The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with validityState.tooShort returning true. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length.
Source: HTML attribute: minlength
Modify last part of your script as below:
form.addEventListener('submit', (event) => {
event.preventDefault();
// your actions
});
Set a minlength value for your input field
<!DOCTYPE html>
<html>
<body>
<h1>The input minlength attribute</h1>
<form action="/action_page.php">
<label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="8"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
image of running code

check php form verifications in when submit form by jquery

i have created form with basic verification in html like this.
<form class="" action="submit/save" method="POST" enctype="multipart/form-data" id="submit_form">
<input class="form-control" name="name" id="name" required>
</form>
<a onclick="submitProduct()">Submit</a>
function submitProduct() {
$('#choice_form').submit();
}
then after click the <a> tag i have submit form as the
$('#submit_form').submit();
but required validations not sporting when submitting
Your code won't submit anything at all, because it's using the wrong ID to identify the form. But assuming that was just a typo then...
Instead of using an anchor tag, just use a regular submit button, then you won't need any script:
<form class="" action="submit/save" method="POST" enctype="multipart/form-data" id="submit_form">
<input type="text" class="form-control" name="name" id="name" required>
</form>
<input type="submit" form="submit_form">Submit</input>
i have entered this jQuery code,
$(document).ready(function(){
$('#submit_form').submit(function(e){
if($(this).closest('form')[0].checkValidity()){
if(submitProduct() == 1 ){
return true;
}else {
return false;
}
}
});
});
submitProduct() is a my another custom function if that function done i have submitted form, if not done then form submission action killed.
$(document).ready(function(){ });
it's helped me to use form validations also like 'required'

How to make sure a form is valid before submitting using JQuery?

I'm trying to make a login page and have the following:
<div id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</div>
I made sure that the username and password fields are required. When the login is successful (for this sake, let's just say that both fields are not empty) a login disappears and another view appears. Anyway, I checked to see if the login button is pressed with JQuery:
$(function(){
$('#submit').on('click', function(){
$('#loginField').hide();
$('#differentView').show();});
The problem is that when the login button is clicked, the required attributes gets ignore and the next view is shown. How do I make sure that the required attributes are not ignored when the login button is clicked?
A crude way of doing it...
<div id="loginField">
<input id="username" type="text" name="user" class="required">
<input id="password" type="password" name="password" class="required">
<input id="submit" type="submit" name="submit" value="Login">
</div>
$('#submit').on('click', function(e){
e.preventDefault();
var isReady = true;
$('.required').each(function(){
if (this.value === '') {
isReady = false;
return;
};
});
if (isReady) {
// submit form
};
});
You can use this library: Parsley. It is a javascript form validation library and it is very easy to use and you can customize it for your own means. Good luck!
Instead of handling onclick on button, you can put input fields into the form...
<form action="post" method="post" id="loginField">
<input id="username" type="text" name="user" required></input>
<input id="password" type="password" name="password" required></input>
<input id="submit" type="submit" name="submit" value="Login"></input>
</form>
... and in jQuery you can handle on submit action like this:
$(document).ready(function(){
$('#loginField').on('submit', function(event){
event.preventDefault();
var [username password] = $(this).serializeArray(),
username = username.value,
password = password.value;
/* some validations */
});
});
event.PreventDefault prevents browser from subbmiting so your page won't be refresh. serializeArray returns an array of objects (key-value) that's why you have to use .value
The required attributes are ignored because the input elements are not inside an html form element
To use the HTML5 input valuation attributes (required, minlength... etc)
The inputs should be grouped inside a form element, and you can listen for the form submit event, that is triggered by default when the user press enter (while focus is on a field inside the form) or clicks the submit button (input or button with type="submit") that is also wrapped inside the form
HTML
<form id="loginForm">
<input id="username" type="text" name="user" required />
<input id="password" type="password" name="password" required />
<input id="submit" type="submit" name="submit" value="Login" />
</form>
Javascript
$(function(){
$('#loginForm').on('submit', function (event) {
event.preventDefault(); // prevent default form submit page reload
console.log('I will enter this handler only on valid form')
$('#loginForm').hide();
$('#differentView').show();
})();
Here is a basic plunker with 2 examples https://plnkr.co/edit/I0vUMSeOlrjlYYu4VofU?p=preview
using the default html5 validation
using Parsley

How to genetrate input field and their value based on user input on the other input field in jquery

I have an input field where user will enter isbn number based on the input number i need to populate two input field i.e book title and book author name i am calling a javscript function on onblur of input and i am getting the correct value but my problem is that if user will not move their cursor from the input field and click on submit button then how i will populate these two input field in these scenario onblur is not working
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number" onblur="getdetail()">
</form>
Pick your preferred solution and adapt it to your website:
1) If your browser supports it, the easiest is make all your fields required and use onchange instead of onblur. This will force the user to enter an isbn, which will trigger the onchange containing more inputs with required.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price" required>
<input type="text" name="isbn_number" id="isbn_number" onchange="getdetail()" required>
</form>
2) Do manual submitting after checking fields.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number" onblur="getdetail()">
<input type="submit">
</form>
<script>
document.querySelector('input[type="submit"]').addEventListener('click', function ( event ) {
var valid = false;
event.preventDefault();
// ...
// add validation code here.
// ...
if (valid) document.querySelector('#post').submit();
});
</script>
3) Only activate the submit if everything is valid.
<form name="post" id="post" method="post" action="#">
<input type="text" name="price" id="price">
<input type="text" name="isbn_number" id="isbn_number">
<input type="submit" disabled="disabled">
</form>
<script>
var valid = false;
document.querySelector('#post').addEventListener('change', function ( event ) {
if (event.target.name === 'isbn_number') getdetail();
// ...
// add validation code
// if (stuff && stuff && stuff) valid = true;
if (valid) document.querySelector('input[type="submit"]').removeAttribute('disabled');
});
</script>

Add an external input value to form on submit

I have a typical form:
<form action="" accept-charset="utf-8" method="post">
<textarea name="content"></textarea>
</form>
and an not-inside-a-form element:
<input type="password" name="password">
How do I add the value of password into the form when I submit the form?
$('form').submit(function(){
//hmmm
});
Create a hidden field in the form and copy the password field value to that field on submit.
Like this.
<form action="" accept-charset="utf-8" method="post">
<textarea name="content"></textarea>
<input type="hidden" name="password" id="ps">
</form>
<input type="password" name="password" id="ps1">
And in on submit function.
$('form').submit(function(){
$('input#ps').val($('input#ps1').val());
return true;
});
The not-yet-supported-but-HTML5-compliant way to do this "correctly" is to give your <input> element a [form] attribute:
<form id="foo">
...stuff...
</form>
<input type="password" id="bar" form="foo" />
Eventually you may be able to use this as a solution, but until more browsers support the [form] attribute, you'll have to polyfill it with JavaScript.
$('form').submit(function(){
var password = $('input[type="password"]');
password.appendTo($(this));
//or $(this).append(password);
});
include a hidden input element inside of the form,
on the outer input's change event, assign the inner input the outer inputs value.
<form action="" accept-charset="utf-8" method="post">
<textarea name="content"></textarea>
<input type="hidden" id="inner" />
</form>
<input type="password" name="password" >
<script type="text/javascript">
$(function(){
$('#outer').change(function(){
$('#inner').val($(this).val());
});
});
</script>
Use hidden input field inside form like this:
ex : <input type="hidden" name="pass">
When you submit the form like this :
$('form').submit(function(){
<!-- Save the value of password into the hidden field
Note : Password here should just be one field in that page -->
$('input[name="pass"]').val($('input[type="password"]').val());
return true;
});

Categories

Resources