Hey i need help to check if email is vaild email...
I tried it with javascript and i dont know how to do it...
Can someone help me to make it please?
My HTML Code :
<input type="text"name="email1" id="MyEmail" placeholder = "Your Email"/>
I want to make an javascript check that the email that the people write is vaild email and if not its will alert them... Please help
i want to check if the new member that want to register to my site is putted a date and that its not empty date (without putting numbers in the date box)
Example just using inline attribute onblur
function check(text) {
var msg = 'Empty';
if (text.value.replace(/\s/g, '')) {
msg = 'Not ' + msg;
}
console.log(msg, text.value);
}
<input type="date" onblur="check(this)" />
<input type="date" onblur="check(this)" />
Above example attaching listeners
let check = function(text) {
var msg = 'Empty';
if (text.value.replace(/\s/g, '')) {
msg = 'Not ' + msg;
}
console.log(msg, text.value);
};
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('input[type="date"]').forEach(function(date) {
date.addEventListener('blur', function(e) {
check(e.target);
});
});
});
<input type="date" /><input type="date" />
You just have add the required attribute to the input tag and remove the unnecessary slash after the max attribute like this:
<form>
<input type="date" id = "Date" min="1905-00-00" max="2019-00-00" required /><br>
<button type="submit">Submit</button>
</form>
You can completely avoid and JavaScript by just adding a preset value to the date. This way users are forced to enter a date no matter what, because the input already starts with a given value. Here is the code:
<input type="date" min="1905-00-00" max="2019-00-00" value="2018-01-01"/>
You can learn more here: https://www.w3schools.com/jsref/prop_date_value.asp
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')">
How to store a flag in a cookie where the flag is true only if a form has been completed?
I have a sidebar contains a form, which when successfully submitted fades the form and display a message using one of the user inputs.
This sidebar form is present over a number of pages on the website. In order to identify if the form has already been completed on another page I believe I can use a flag variable to define whether this is true or false and then display the form or the message depending on the stored value.
I have never used cookies as a medium to store a value and do not know the correct syntax for them. Can I simply make the cookie when the formsubmit is successful. And on every page have a script in the header that will then be read to either display the form or not.
Is this the best way to go about this? And what is the format and correct syntax to identify something like this?
HTML
<div id="sidebarf">
<form id="sidebarform" onsubmit="return false" method="post" name="myForm" autocomplete="off" >
<input type="text" name="name" id="username" placeholder="Name (eg. Rob James)" value="" required><br><br>
<input type="text" name="location" id="userlocation" placeholder="Location (eg. Wacol)" value="" required><br><br>
<input type="text" name="postcode" id="userpc" pattern="[0-9]{4}" placeholder="Postcode (eg. 4076)" maxlength="4" value="" required> <br><br>
<input type="email" name="email" id="useremail" placeholder="Email Address (eg. someone#yourdomain.com" value="" required> <br><br>
<input type="tel" name="phone" id="userphone" placeholder="Phone Number (eg. 0412345678)" maxlength="10" minlength="6" value="" required> <br><br>
<textarea rows="4" cols="20" id="usercomment" placeholder="Comment/Question" value="" required></textarea><br><br>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
</div>
JAVASCRIPT
$("#sidebarform").on("submit", function() {
if ($("#username").val() == "") {
return false;
}
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("Thankyou for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
});
return false;
/////////////////Is this the flag?/Correct Location?//////////////
//////var completed = true
//////document.cookie=completed;
///////////
});
</script>
And then would I call something like this when the page loads?
///////////////////DOES NOT WORK/////////////////
<script>
function checkCookie()
{
var display=getCookie("completed");
if (complete!="true")
{
$("#sidebarf").html("Thankyou for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
}
else
{
$("#sidebarf").html //(Don't know what to put here!)
}
}
I also have this for a custom validity after the above code. But this shouldn't play a role.
$(document).ready(function () {
$('#username').on({
invalid: function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter a name.");
}
},
input: function(e) {
e.target.setCustomValidity("");
}
});
As I said, I honestly have no idea about the cookie use so the code is just what I've search on the web.
If you use this jQuery cookie plugin you can simplify your code a great deal. The following code should check for the cookie when the page loads. If the cookie is found, the form is immediately hidden without animation. Otherwise when the form is submitted, the cookie is set so that at the next page load the form will be hidden.
$(function() {
var completed = $.cookie( 'completed' ),
form = $('#sidebarform'),
msg = $('#sidebarf');
if( ( completed != undefined ) && ( completed == 'done' ) ) {
form.hide();
msg.html( 'Form already completed.' );
}
form.on("submit", function( e ) {
e.preventDefault();
if ( $("#username").val() == "" ) {
return false;
}
$(this).fadeOut("slow", function() {
msg.html("Thank you for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
form.submit();
//or submit form via ajax ---> YOUR CHOICE
$.cookie( 'completed', 'done' );
});
});
});
JS FIDDLE DEMO
I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.
I've got the following HTML form: http://jsfiddle.net/nfgfP/
<form id="form" onsubmit="return(login())">
<input name="username" placeholder="Username" required />
<input name="pass" type="password" placeholder="Password" required/>
<br/>Remember me: <input type="checkbox" name="remember" value="true" /><br/>
<input type="submit" name="submit" value="Log In"/>
Currently when I hit enter when they're both blank, a popup box appears saying "Please fill out this field". How would I change that default message to "This field cannot be left blank"?
The type password field's error message is simply *****. To recreate this give the username a value and hit submit.
Here is some code to display a custom error message:
<input type="text" id="username" required placeholder="Enter Name"
oninvalid="ths.setCustomValidity('Enter User Name Here')"
oninput="setCustomValidity('')"/>
This part is important because it hides the error message when the user inputs new data:
oninput="setCustomValidity('')"
Note: the this keyword is not required for inline event handlers, but you may want to use it anyway for consistency.
Use setCustomValidity:
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field cannot be left blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
I changed to vanilla JavaScript from Mootools as suggested by #itpastorn in the comments, but you should be able to work out the Mootools equivalent if necessary.
If setCustomValidity is set to anything other than the empty string it will cause the field to be considered invalid; therefore you must clear it before testing validity, you can't just set it and forget.
As pointed out in #thomasvdb's comment below, you need to clear the custom validity in some event outside of invalid otherwise there may be an extra pass through the oninvalid handler to clear it.
It's very simple to control custom messages with the help of HTML5 event oninvalid
Here is code:
<input id="UserID" type="text" required="required"
oninvalid="this.setCustomValidity('Witinnovation')"
onvalid="this.setCustomValidity('')">
This is most important:
onvalid="this.setCustomValidity('')"
Note: This no longer works in Chrome, not tested in other browsers. See edits below. This answer is being left here for historical reference.
If you feel that the validation string really should not be set by code, you can set you input element's title attribute to read "This field cannot be left blank". (Works in Chrome 10)
title="This field should not be left blank."
See http://jsfiddle.net/kaleb/nfgfP/8/
And in Firefox, you can add this attribute:
x-moz-errormessage="This field should not be left blank."
Edit
This seems to have changed since I originally wrote this answer. Now adding a title does not change the validity message, it just adds an addendum to the message. The fiddle above still applies.
Edit 2
Chrome now does nothing with the title attribute as of Chrome 51. I am not sure in which version this changed.
It's very simple to control custom messages with the help of the HTML5 oninvalid event
Here is the code:
User ID
<input id="UserID" type="text" required
oninvalid="this.setCustomValidity('User ID is a must')">
By setting and unsetting the setCustomValidity in the right time, the validation message will work flawlessly.
<input name="Username" required
oninvalid="this.setCustomValidity('Username cannot be empty.')"
onchange="this.setCustomValidity('')" type="text" />
I used onchange instead of oninput which is more general and occurs when the value is changed in any condition even through JavaScript.
I have made a small library to ease changing and translating the error messages. You can even change the texts by error type which is currently not available using title in Chrome or x-moz-errormessage in Firefox. Go check it out on GitHub, and give feedback.
It's used like:
<input type="email" required data-errormessage-value-missing="Please input something">
There's a demo available at jsFiddle.
Try this one, its better and tested:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
</form>
Demo:
http://jsfiddle.net/patelriki13/Sqq8e/
The easiest and cleanest way I've found is to use a data attribute to store your custom error. Test the node for validity and handle the error by using some custom html.
le javascript
if(node.validity.patternMismatch)
{
message = node.dataset.patternError;
}
and some super HTML5
<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>
The solution for preventing Google Chrome error messages on input each symbol:
<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>
<form method="post" action="#">
<label for="text_number_1">Here you will see browser's error validation message on input:</label><br>
<input id="test_number_1" type="number" min="0" required="true"
oninput="this.setCustomValidity('')"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>
<form method="post" action="#">
<p></p>
<label for="text_number_1">Here you will see no error messages on input:</label><br>
<input id="test_number_2" type="number" min="0" required="true"
oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>
I have a simpler vanilla js only solution:
For checkboxes:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.checked ? '' : 'My message');
};
For inputs:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.value ? '' : 'My message');
};
Okay, oninvalid works well but it shows error even if user entered valid data. So I have used below to tackle it, hope it will work for you as well,
oninvalid="this.setCustomValidity('Your custom message.')" onkeyup="setCustomValidity('')"
If your error message is a single one, then try below.
<input oninvalid="this.setCustomValidity('my error message')"
oninput="this.setCustomValidity('')"> <!-- 👈 don't forget it. -->
To handle multiple errors, try below
<input oninput="this.setCustomValidity('')">
<script>
inputElem.addEventListener("invalid", ()=>{
if (inputElem.validity.patternMismatch) {
return inputElem.setCustomValidity('my error message')
}
return inputElem.setCustomValidity('') // default message
})
</script>
Example
You can test valueMissing and valueMissing.
<form>
<input pattern="[^\\/:\x22*?<>|]+"
placeholder="input file name"
oninput="this.setCustomValidity('')"
required
>
<input type="submit">
</form>
<script>
const form = document.querySelector("form")
const inputElem = document.querySelector(`input`)
inputElem.addEventListener("invalid", ()=>{
if (inputElem.validity.patternMismatch) {
return inputElem.setCustomValidity('Illegal Filename Characters \\/:\x22?<>|')
}
return inputElem.setCustomValidity('') // return default message according inputElem.validity.{badInput, customError, tooLong, valueMissing ...}
})
form.onsubmit = () => {
return false
}
</script>
ValidityState
const username= document.querySelector('#username');
const submit=document.querySelector('#submit');
submit.addEventListener('click',()=>{
if(username.validity.typeMismatch){
username.setCustomValidity('Please enter User Name');
}else{
username.setCustomValidity('');
}
if(pass.validity.typeMismatch){
pass.setCustomValidity('Please enter Password');
}else{
pass.setCustomValidity('');
}
})
Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/> field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.
I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:
Hello.js
import React, { Component } from "react";
import SelectValid from "./SelectValid";
export default class Hello extends Component {
render() {
return (
<form>
<SelectValid placeholder="this one is optional" />
<SelectValid placeholder="this one is required" required />
<input
required
defaultValue="foo"
onChange={e => e.target.setCustomValidity("")}
onInvalid={e => e.target.setCustomValidity("foo")}
/>
<button>button</button>
</form>
);
}
}
SelectValid.js
import React, { Component } from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";
export default class SelectValid extends Component {
render() {
this.required = !this.props.required
? false
: this.state && this.state.value ? false : true;
let inputProps = undefined;
let onInputChange = undefined;
if (this.props.required) {
inputProps = {
onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
};
onInputChange = value => {
this.selectComponent.input.input.setCustomValidity(
value
? ""
: this.required
? "foo"
: this.selectComponent.props.value ? "" : "foo"
);
return value;
};
}
return (
<Select
onChange={value => {
this.required = !this.props.required ? false : value ? false : true;
let state = this && this.state ? this.state : { value: null };
state.value = value;
this.setState(state);
if (this.props.onChange) {
this.props.onChange();
}
}}
value={this && this.state ? this.state.value : null}
options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
placeholder={this.props.placeholder}
required={this.required}
clearable
searchable
inputProps={inputProps}
ref={input => (this.selectComponent = input)}
onInputChange={onInputChange}
/>
);
}
}
For a totaly custom check logic:
$(document).ready(function() {
$('#form').on('submit', function(e) {
if ($('#customCheck').val() != 'apple') {
$('#customCheck')[0].setCustomValidity('Custom error here! "apple" is the magic word');
$('#customCheck')[0].reportValidity();
e.preventDefault();
}
});
$('#customCheck').on('input', function() {
$('#customCheck')[0].setCustomValidity('');
});
});
input {
display: block;
margin-top: 15px;
}
input[type="text"] {
min-width: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="text" placeholder="dafault check with 'required' TAG" required/>
<input type="text" placeholder="custom check for word 'apple'" id="customCheck" />
<input type="submit">
</form>
Can be easily handled by just putting 'title' with the field:
<input type="text" id="username" required title="This field can not be empty" />