Not allow a blank character / space in a input form [duplicate] - javascript

This question already has answers here:
How to prevent invalid characters from being typed into input fields
(8 answers)
Closed 9 years ago.
Is it possible to not allow a blank character / space in a input form like below?
<input type="text" value="" maxlength="30" name="email" class="formfield w0">

Check this Fiddle. Relevant code:
$(function() {
$('#input1').on('keypress', function(e) {
if (e.which == 32){
console.log('Space Detected');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1" />

Use HTML5's extended input types to apply constraint validation, which will prevent submitting the form with invalid emails in modern browsers:
<input type="email" value="" maxlength="30" name="email" class="formfield w0">
In older browsers, you can detect that the input's type is not "email", as it will default to "text" when a value is considered invalid. I'd recommend blocking the submission of the form, rather than preventing default action of the space key, which could be inadvertently circumvented by pasting or via other input methods.
The following code is an example of this, and should be executed after the document is ready:
var frm = document.getElementById('myform');
if (frm.email.type === 'text') {
frm.onsubmit = function () {
if (/\s/.test(frm.email.value)) {
// Tell your user the field is invalid here, e.g.
frm.email.className = 'invalid';
// Prevent form submission
return false;
}
}
}
Working demo: http://jsfiddle.net/hgc7C/
Don't forget that this is not a substitute for server-side form validation.

Yes it is possible by using javascript/JQuery.
If you want it for all text boxes, then do as below.
$(function() {
$('.formfield input[type=text]').on('keypress', function(e) {
if (e.which == 32)
return false;
});
});
If you want it for a specific textbox, then add an id to the textbox input and replace .formfield input[type=text] with #textBoxId

Related

Why is setCustomValidity('') ignored on input (Chrome 65)

Note: to the best of my knowledge this question is not a duplicate question of the following:
HTML5: Why does my “oninvalid” attribute let the pattern fail?
HTML5 form required attribute. Set custom validation message?
How can I change or remove HTML5 form validation default error messages?
Overview
Given a field that:
Has pattern attribute set for validation, for example "[a-f,0-9]{4}" for a 4 character hex string input.
Has oninvalid set with setCustomValidity('...some message...') to define a custom validation message
Has oninput set with setCustomValidity('') to reset on input
Here is an example showing this:
/* jshint esnext: true */
const form = document.querySelector("#form");
const field = document.querySelector("#field");
const output = document.querySelector("#output");
form.addEventListener('submit', (e) => {
console.log("SUBMIT");
output.textContent = field.value;
e.preventDefault(); // Prevent default POST request
});
field.oninvalid = (event) => {
console.log("INVALID");
event.target.setCustomValidity('must be valid 4 hex characters');
}
field.oninput = (event) => {
console.log("INPUT");
event.target.setCustomValidity('');
}
Output: <span id="output">No output</span>
<form id="form">
<label for="field">Enter 4 character hex code: </label>
<input id="field" type="text" pattern="[a-f,0-9]{4}" autocomplete=off>
</form>
Validation works almost as desired, except when the user enters an invalid entry and then proceeds to try and edit it, where their following input states are still invalid:
At this point, neither the custom setCustomValidity message defined in oninvalid is used, nor the empty one defined in onInput.
Instead, as long as the field is in an invalid state and not blurred, the default Please match the requested format. message appears.
Question
What is going on here? Looking at the console, the oninput event is called each time, and therefore event.target.setCustomValidity(''); is called each time.
So why is it that we are still seeing the generic default validation message? Shouldn't setCustomValidity('') disable that?
An acceptable answer here should exhibit the following:
The parameter field is respected for validation.
Any validation message appears if and only if the user attempts to submit an invalid field and not when they modify the input immediately afterward.
The default Please match the requested format. message never appears at all.
It appears that this is a bug with Chrome 65 in windows.
using setCustomValidity('') in oninput should disable the default validation messages appearing on input.
The following workaround works for me:
/* jshint esnext: true */
const form = document.querySelector("#form");
const field = document.querySelector("#field");
const output = document.querySelector("#output");
const pattern = field.getAttribute("pattern");
form.addEventListener('submit', (e) => {
console.log("SUBMIT");
output.textContent = `User submitted: ${field.value}`;
e.preventDefault(); // Prevent default POST request
});
field.oninvalid = (event) => {
console.log("INVALID");
event.target.setCustomValidity('must be valid 4 hex characters');
}
field.oninput = (event) => {
console.log("INPUT");
event.target.setCustomValidity('');
event.target.removeAttribute("pattern");
}
field.onchange = (event) => {
console.log("CHANGE");
event.target.setAttribute("pattern", pattern);
}
Output: <span id="output">No output</span>
<form id="form">
<label for="field">Enter 4 character hex code: </label>
<input id="field" type="text" pattern="[a-f,0-9]{4}" autocomplete=off>
</form>
setCustomValidity is meant to be used when multiple inputs, in combination are invalid. That is why it has to be reset to the empty string manually after. Other wise the title attribute should be used.
Trying to hide the validation error after editing the input is understandable but it is against the HTML5 form philosophy. It is meant to be shown as long as the input is invalid.
Adding maxlength can help the user to not cross the upper limit.
If you really want your bullet points to be satisfied feel free to not use HTML5 form validation but something custom instead.
So the reason a tooltip is shown even when setCustomValidity is set to empty string is because the input element is still invalid as per pattern attribute.
<form id="form">
<label for="field">Enter 4 character hex code: </label>
<input id="field" type="text" pattern="[a-f,0-9]{4}" maxlength="4" minlength="4" autocomplete="off" title="must be valid 4 hex characters">
</form>
JS
const form = document.querySelector("#form");
const field = document.querySelector("#field");
const output = document.querySelector("#output");
form.addEventListener('submit', (e) => {
console.log("SUBMIT");
output.textContent = field.value;
e.preventDefault(); // Prevent default POST request
});
field.oninvalid = (event) => {
console.log("INVALID");
}
field.oninput = (event) => {
console.log("INPUT");
}

Is it possible to detect which input field was invalid upon form submit?

Using the code below, I am able to use .on("invalid") function to detect if there was an error with a field when submitting a form. If there was an error, I then check if both the input and textarea if either of them or empty, too long or too short and add the class .error.
However I am wondering if there is any way to simplify my code so that I don't have to run additional if statements inside the function.
$("form input, form textarea").on("invalid", function(event) {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (!input1.value || input1.value.length < 9 || input1.value.length > 69) {
input1.classList.add('error');
setTimeout(function() {
input1.classList.remove('error');
}, 500);
}
if (!input2.value || input2.value.length < 21 || input2.value.length > 899) {
input2.classList.add('error');
setTimeout(function() {
input2.classList.remove('error');
}, 500);
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" minlength="8" maxlength="70" required>
<textarea id="input2" maxlength="900" required></textarea>
<input type="submit">
</form>
Here is an example of what I am looking for, where x is the field (the input or textarea) which caused the form to be invalid.:
$("form input, form textarea").on("invalid", function(event) {
x.classList.add('error'); // variable x
setTimeout(function() {
x.classList.remove('error'); // variable x
}, 500);
});
I would ideally like to stick to JavaScript, however I appreciate that jQuery may be needed.
Here is a possible solution that doesn't exactly find the target with javascript, but uses the oninvalid event listener in html.
<input type="text" oninvalid="alert('You must fill out the form!');" required>
When the form returns invalid, instead of it being packaged as a form event, this will trigger as an input event. You can make it do whatever you like in javascript when that specific input is incorrect upon form submission.
https://www.w3schools.com/jsref/event_onsubmit.asp
The event onsubmit perhaps will be a better option. Is valid for all browsers
https://www.w3schools.com/jsref/event_oninvalid.asp
Instead, if you use oninvalid you will find problems with the Safari browser
<form onsubmit="validateForm()">
Enter name: <input type="text">
<input type="submit">
</form>
function validateForm() {
//your code here
if(validationfails){
return false; //if arrives here means the form won't be submited
}
}
I was able to solve this, particularly thanks to the suggestion by John Paul Penaloza, by using oninvalid on the input and textarea field. I called a function which then added the class .error to the input field - it does the same as the code in my question, but simpler:
function error(field) {
field.classList.add('error');
setTimeout(function() {
field.classList.remove('error');
}, 500);
}
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" oninvalid="error(this);" minlength="8" maxlength="70" required>
<textarea id="input2" oninvalid="error(this);" maxlength="900" required></textarea>
<input type="submit">
</form>
Or you can think differently and offer real time error reporting.
Add an id="myForm" to your <form> element, and then use Js in a lines of:
var allInputs = $('#myForm :input');
var inputsFuked = []
allInputs.each(function( index ) {
console.log(allInputs[index]);
$(allInputs[index]).change(function() {
if (allInputs[index].checkValidity()) inputsFuked[index]=1;
else inputsFuked[index]=0;
});
});
Here is working JSfiddle with couple of more elements without validation.
This will bind on change code to be executed every time some input changes. This is an example so it only toggles values in array. When you wanna validate, you simply check which are wrong. If you stored elements in array you could state which element. Simply switch toggle index logic to add/remove from array.
But with this contraption you can do way better, you can write instant reaction to invalid element. Instead changing index in array you could prompt alert, display error, make element red. Basically interact with the user the moment he focused out of element where he made input error instead doing it passively at some point after.

JQuery and HTML5 custom validation not working as intended

I just started learning JS, Jquery and HTML online. I have a question, and have tried doing things which were told in the answers of similar questions on SO, but it won't help.
I have a password form which only accepts input which have atleast 6 characters, one uppercase letter and one number. I wish to show a custom validation message which could just state these conditions again.
Here's my HTML code -
<div class="password">
<label for="password"> Password </label>
<input type="password" class="passwrdforsignup" name="password" required pattern="(?=.*\d)(?=.*[A-Z]).{6,}"> <!--pw must contain atleast 6 characters, one uppercase and one number-->
</div>
I'm using JS to set the custom validation message.
JS code
$(document).ready(function () {
$('.password').on('keyup', '.passwrdforsignup', function () {
var getPW = $(this).value();
if (getPW.checkValidity() === false) {
getPW.setCustomValidity("This password doesn't match the format specified");
}
});
});
However, the custom validation message doesn't show. Please help. Thank you so much in advance! :)
UPDATE 1
I changed the password pattern to (?=.*\d)(?=.*[A-Z])(.{6,}). Based on 4castle's advise, I realized there were a few errors in my javascript, and changed them accordingly. However, the custom validation message still doesn't show.
JavaScript:
$(document).ready(function () {
$('.password').on('keyup', '.passwrdforsignup', function () {
var getPW = $(this).find('.passwrdforsignup').get();
if (getPW.checkValidity() === false) {
getPW.setCustomValidity("This password doesn't match the format specified");
}
});
});
Again, than you all in advance!
First, update this:
var getPW = $(this).find('.passwrdforsignup').get();
to this:
var getPW = $(this).get(0);
...because $(this) is already the textbox .passwrdforsignup, you can't find it in itself!
The problem with setCustomValidity is, that it does only work once you submit the form. So there is the option to do exactly that:
$(function () {
$('.password').on('keyup', '.passwrdforsignup', function () {
var getPW = $(this).get(0);
getPW.setCustomValidity("");
if (getPW.checkValidity() === false) {
getPW.setCustomValidity("This password doesn't match the format specified");
$('#do_submit').click();
}
});
});
Please note the getPW.setCustomValidity(""); which resets the message which is important because if you do not do this, getPW.checkValidity() will always be false!
For this to work the textbox (and the submit-button) must be in a form.
Working JSFiddle
There are several issues going on here.
The pattern doesn't have a capture group, so technically nothing can ever match it. Change the pattern to (?=.*\d)(?=.*[A-Z])(.{6,})
$(this).value() doesn't refer to the value of the input tag, it's referring to the value of .password which is the container div.
getPW.checkValidity() and getPW.setCustomValidity("blah") are getting run on a string, which doesn't have definitions for those functions, only DOM objects do.
Here is what you should do instead (JS code from this SO answer)
$(document).ready(function() {
$('.passwrdforsignup').on('invalid', function(e) {
var getPW = e.target;
getPW.setCustomValidity("");
if (!getPW.checkValidity())
getPW.setCustomValidity("This password doesn't match the format specified");
}).on('input', function(e) {
$(this).get().setCustomValidity("");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="password">
<label for="password">Password</label>
<input type="password" class="passwrdforsignup" name="password"
required pattern="(?=.*\d)(?=.*[A-Z])(.{6,})" />
</div>
<input type="submit" />
</form>

Validation for HTML5 Input Range

How can I add a validation for the html5 input type range?
It should not be 0. How can I add a warning message, like the default validation messages on other html5 input types?
Example: <input type="number" size="6" name="age" min="18" max="99" value="21">
Some more examples: HTML5 Validation Types
I'd add the pattern attribute:
pattern="[1-1000]"
That requires a number entered between 1 and 1000
I'd also add:
required="required"
You can check if the user press the key with an eventlistener via jquery and prevent the use of it
$("input").addEventListener("keypress", function (evt) {
/*your condition*/
if ( evt.which == /*your keycode*/ )
{
evt.preventDefault();
alert(); /*you error message/code*/
}
});
http://www.webonweboff.com/tips/js/event_key_codes.aspx

How to create html5 custom validation?

I am using html 5 form validation for validate my form before submit, if is valid, submit, but I need validate my User Register form, so it need validate if Password Confirm value is equal camp Password, below is my form example:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
or in jsfiddle
How to can I create my custom validation for work like default validations?
Well you can use JQuery and attach an attribute to be selected for the passwords to validate each other via input event. Use setCustomValidity() to set the message of the input affected to override the default message when the form is submitted.
See the updated fiddle.
As you can see in the fiddle, all you have to do is add an attribute data-equal-id wherein the attribute value must be the ID of password input element to be tested.
HTML
<h1>How to create html5 validation for password confirm?</h1>
<hr>
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf" data-equal-id="pass" /><br/>
<input type="submit"/>
</form>
Javascript
$('[data-equal-id]').bind('input', function() {
var to_confirm = $(this);
var to_equal = $('#' + to_confirm.data('equalId'));
if(to_confirm.val() != to_equal.val())
this.setCustomValidity('Password must be equal');
else
this.setCustomValidity('');
});
you could try putting this code in your header:
<script>
document.getElementById('myform').onsubmit = function() {
if(!validateForm()){ // call your validation function
alert('fail!'); // remove this
return false; // prevent the form to submit
}
}
// your validation function
// compares that the passwords are equal
function validateForm(){
var pass = document.getElementById('pass').value;
var pass_conf = document.getElementById('pass_conf').value;
if(pass == pass_conf){
return true;
}else{
return false;
}
}
</script>
also put the id 'myform' to your form (or the name you want, but change it in the first line)
How about something fun like this using jQuery?
$('input[type="password"]').keyup(function() {
var pass=$('#pass').val();
var conf=$('#pass_conf').val();
if (pass == conf)
$('input[type="submit"]').removeAttr('disabled');
else
$('input[type="submit"]').attr('disabled', 'disabled');
});
The breakdown...
I am keying off of the keyup, so every time a key is pressed in the
password fields the function will fire.
I'm grabbing the value of both password fields, and comparing them.
If the values are the same, I'm enabling the submit button.
If the values are different, I'm disabling the submit button.
Pretty simple, but it works. Here is a demo: http://codepen.io/anon/pen/GxAyC/
(note - I added a couple of other visual enhancements to the demo to show what can be done)
You're using HTML5 for client-side form validation and wish to validate your form prior to form submission. Your form consists of three inputs and your only validation criteria is that both password fields match.
The most simple way to do this is to write a custom submit handler script:
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass === form.pass_conf) {
form.submit();
}
}
Above preventDefault() stops the default form submission behavior so you can execute your check. Then check if the value of the two password fields are equal. And if they are, continue form submission.
To use, attach the custom handler to your form by listening to the submit event:
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
Applied in context to example form provided:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass.value === form.pass_conf.value) {
form.submit();
}
}
</script>

Categories

Resources