custom error message with more html validate - javascript

Hello I want to create a custom error alert in HTML
here I want to custom in( required) and another for ( max and min number)
<div class="form-group">
<label for="durationdays">Days</label><br>
<input type="number" name="duration" max="5" min="1" class="form-control" style="width:50%" required oninvalid="InvalidMsg(this);" oninput="InvalidMsg(this);">
</div>
and this is a javascript code
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity
('Required');
} else if (textbox.validity.typeMismatch) {
textbox.setCustomValidity
('ONlY number');
} else {
textbox.setCustomValidity('');
}
return true;
}
I want if the user clicks on send button with empty value show this(Required)
and if enter letter value show (ONLY number)
and if enter less than 1 or more than 5 show (should be less than or equal 5)

You can use textbox.setCustomValidity(`Max: ${textbox.max} Min:${textbox.min}`); to get the min and max values, then it's possible to show the numbers. The other ones should work fine.

Related

16 Digit Validation using JQUERY

I am trying to validate a text field to 16 digits only. How can I do this using JQUERY?
Here is the text field
<input type="card" class="form-control" id="card" placeholder="Enter Credit Card" name="card">
if ( $.isNumeric(value) && value.length == 16 ) {
// pass
} else {
// fail
}
Pun in input maxlength="15"

javascript enter number of seconds - not less than zero

i am facing an issue in javascript. i want to do user enter number of seconds in input field.
but the condition is that users can't enter number of seconds less than zero.
how can a make the code logic?
function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds">
<button onclick="sec()">Click</button>
</form>
what should i do? anyone help me?
Add your expectation about the input value as attributes on your input:
Specifically required min="0" would meet your needs.
function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds" required min="0">
<button onclick="sec()">Click</button>
</form>
With JavaScript you can convert your user's input to a Number then check its value with an equality condition.
E.g. you could fill out your sec() function like this:
function sec() {
const seconds_str = document.getElementById("seconds").value;
const seconds_num = parseInt(seconds_str, 10); // note: you could use parseFloat for decimal fractions
let result = "";
if (seconds_num < 0) {
result = "Is less than zero :'(";
} else {
result = "Is NOT less than zero :)";
}
console.log("User input = " + seconds_str);
console.log("Converted to integer = " + seconds_num);
console.log(result);
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds">
<button onclick="sec()" type="button">Click</button>
</form>
It would be up to you what you do when you detect a number less than zero. E.g. prevent form submitting, show an error message etc...

HTML input type=number step prevents form from submitting

I have this code in HTML:
<input type="number" step="0.1" class="form-group">
I want the user to be able to enter a 3-digit decimal number like 1.234 but step needs to be 0.1 and it throws an error and prevents the form from submitting.
I've already tried step="0.100" but the result was the same.
I also need to validate other inputs so I can't use no validate in the <form> tag.
What needs to be done?
I'd write a small customized built-in custom element doing just that:
class MyInput extends HTMLInputElement {
constructor(step = 0.1, value = '') {
super();
this.type = 'number';
this.step = this.getAttribute('step') || step;
this.value = this.getAttribute('value') || value;
this.addEventListener('input', (e) => {
this.value = parseFloat(this.value) + 0.034;
})
}
}
customElements.define('my-input', MyInput, { extends: 'input' });
let input = new MyInput(0.1, 1);
document.body.appendChild(input);
<!-- if you want to use declaratively: -->
<input is="my-input" step="0.1" value="2" />
<hr />
This definitely needs some tweaking, e.g. if the user types in the input, but this should serve you well as a starting point.
One thought is you could remove the step attribute, disable the +/- slider buttons, and implement your own +/- buttons. Then, when a user clicks those buttons, a JavaScript function is called that retrieves the value in the input area, converts it to a number, and performs the desired step.
You might run into precision issues with using a step like 0.1. In the below snippet I just fixed the number of decimal places to two.
function stepUp(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num + step).toFixed(2);
}
function stepDown(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num - step).toFixed(2);
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
<button onclick="stepDown(0.1)">-</button>
<input id="value" type="number" value="0.00">
<button onclick="stepUp(0.1)">+</button>
You can use novalidate and write your own validation in js for other form fields
<form novalidate>
<input type="number" step="0.1" class="form-group" >
<button>submit</button>
</form>

HTML5 Form validation - error message customization

I have a form with an input like this.
<input type="text" name="question" class="form-control" required="" minlength="4" maxlength="2" size="20" oninvalid="setCustomValidity('please enter something')">
Now the default validation messages work great. But I want to set custom messages for specific rules.
i.e. for rules like required minlength maxlength when each fails I want to provide a custom error message specific to the rule that failed.
I have tried oninvalid="setCustomValidity('please enter something')" but that sets that message for every rule.
How can I specify custom error messages for specific rules?
Use setCustomValidity property to change validation messages and validity property to find type of validation error
validity : A ValidityState object describing the validity state of the element.
Upon form load validate property is initialized for each form element and updated on every validation due to user events like keypress,change etc. Here you can find the possible values
var email = document.getElementById("mail");
if (email.validity.valueMissing) {
email.setCustomValidity("Don't be shy !");
}
else{
event.target.setCustomValidity("");
}
email.addEventListener("input", function (event) {
if (email.validity.valueMissing) {
event.target.setCustomValidity("Don't be shy !");
}
else{
event.target.setCustomValidity("");
}
});
Demo https://jsfiddle.net/91kc2c9a/2/
Note: For some unknown reason email validation is not working in the above fiddle but should work fine locally
More on ValidityState here
The oninvalid event occurs when the input is invalid, in your case, the input is required and if it is empty, oninvalid will occur. (see this)
And yes, maxlength should be bigger than minlength and instead of required="" you can simply write required
if your code is like this (with an ID 'input-field'):
<input type="text" name="question" id="input-field" class="form-control" required="" minlength="4" maxlength="8" size="20" oninvalid="setCustomValidity('please enter something')">
You will need to add custom functions to check different validation and display different errors based on them.
The validator() function bellow triggers when the input box loses focus and checks for its requirements, and the valdiator_two() is triggered on every keypress in the input field:
var field = document.getElementById("input-field");
function validator(){
if (field.value === "") {
alert("You can't leave this empty");
}
if (field.value !== "" && field.value.length < 4){
alert("You have to enter at least 4 character");
}
}
function validator_two(){
if (field.value.length >= 8){
alert("You can't enter more than 8 character");
}
}
field.addEventListener("blur", validator);
field.addEventListener("input", validator_two);
<input type="text" name="question" id="input-field" class="form-control" required="" minlength="4" maxlength="8" size="20" oninvalid="setCustomValidity('please enter something')">

If condition is true print text in input field with specific ID

Noob in need of some input here. I've spent some hours now trying to get this to work, with both PHP and javascript and this is where i'm at now.
I want to get an input field to show a specific text based on a condition. If the digit in input field 'ebctotal' is within the range 1-4, then show the text "very pale" in input field 'hue'.
Code:
function getHue() {
var ebc = document.getElementById("ebctotal").value;
if (ebc >= 1 && ebc <= 4) {
// insert text "Very pale" into element with id 'hue'
document.getElementById('hue').value;
}
}
HTML:
// print text in this field
<input class="input" type="text" id="hue" size="7" maxlength="20">
// based on value of this field
<input class="input" type="text" id="ebctotal" size="7" maxlength="20">
Am I on the right track?
Cheers
If you want to check whether length of "ebc" between 1-4 then try like;
function getHue() {
var ebc = document.getElementById("ebctotal").value;
if (ebc.length>=1 && ebc.length<=4) {
document.getElementById('hue').value='Very pale';
}
}
or whether value of "ebc" between 1-4 then try like;
function getHue() {
var ebc = parseInt(document.getElementById("ebctotal").value);
if (ebc>=1 && ebc<=4) {
document.getElementById('hue').value='Very pale';
}
}

Categories