Note: this is a jQuery coding exercise and I am not allowed to use plugins or other modules.
I have a simple form validation script. When the user enters in data and it's empty the appropriate error gets displayed.
When the user types in the required field and submits the form again I want the error message to disappear if it's no longer empty and show the appropriate error if other fields are still empty.
I tried the following and the errors still show after entering the required form fields and a resubmission is done.
jsfiddle
HTML
<form id="myForm">
<input type="text" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span><br />
<input type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span><br />
<input type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span><br />
<input type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span><br />
<input type="submit" value="Submit">
</form>
CSS
.error {
display: none;
}
.error_show {
display: inline-block;
color: red;
margin-bottom: 1em;
}
jQuery
// jQuery form validation
$(document).ready(function(){
// remove class from previous data entry
$('#myform span').removeClass('error_show');
// field mapping
var form_fields = {
'email' : 'email',
'pword' : 'password',
'fname' : 'first name',
'lname' : 'last name'
};
// ajax data
var data = {};
// make sure form fields were entered
$('#myForm').on('submit', function(e){
for (var field in form_fields) {
if (!$('#' + field).val()) {
$('#' + field).next().addClass('error_show');
} else if ($('#' + field).val()) {
data[field] = $('#' + field).val();
}
}
return false;
});
});
Just add removeClass() to the else branch of your validation function:
// jquery form validation
$(document).ready(function(){
// remove class from previous data entry
$('#myform span').removeClass('error_show');
// field mapping
var form_fields = {
'email' : 'email',
'pword' : 'password',
'fname' : 'first name',
'lname' : 'last name'
};
// ajax data
var data = {};
// make sure form fields were entered
$('#myForm').on('submit', function(e){
for (var field in form_fields) {
if (!$('#' + field).val()) {
$('#' + field).next().addClass('error_show');
} else if ($('#' + field).val()) {
$('#' + field).next().removeClass('error_show'); // <-- Here .removeClass() is added
data[field] = $('#' + field).val();
}
}
return false;
});
});
Now the class gets removed when the field has a value.
Demo: https://jsfiddle.net/mxjvu95n/1/
Related
The small code in pure HTML, without forgetting to set the method for get:
<form action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome"><br>
<input id="email" type="text" name="email" placeholder="E-mail"><br>
<textarea id="message" name="name" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio"></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
I refactored and made a clean code of the dirty multiple if-else statements, simplifying. After it, I can not trigger the alert.
The code let send = document.getElementById("send"); checks the code <input type="submit" value="Enviar" id="send"><br>.
Before, in a dirty code, I had many document.getElementById("email").value == "" and simplified to:
const fields = new Set([
'name',
'email',
'message',
]);
I simplified three 'if-else statements along with these if-else statements of identifiers. Firstly, it will check if the fields are empty, go to verify the length, 1 indicates only an empty field and > 1 indicates more empty fields. Else they will check the fields are full and submit.
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Thank you! The message was sent successfully")
}
}
Finally, the code send.addEventListener("click", alert) indicates to click the function when sending, and addEventListener will trigger the alert.
Complete code in JavaScript:
let send = document.getElementById("send");
const fields = new Set([
'name',
'email',
'message',
]);
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Agradecemos, mensagem enviada com sucesso!")
}
}
send.addEventListener("click", alert)
I will suggest that you create an event listener for invalid on the form. This will be called when one of the required fields empty/invalid (see the required attribute on all the fields). I made a custom alert that shows.
var alert = document.getElementById('alert');
alert.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON')
alert.classList.remove('show');
});
document.forms.form01.addEventListener('submit', e => {
console.log('The form will submit');
});
document.forms.form01.addEventListener('invalid', e => {
e.preventDefault();
alert.classList.add('show');
}, true);
#alert {
display: none;
}
#alert.show {
display: block;
}
<form name="form01" action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome" required><br>
<input id="email" type="text" name="email" placeholder="E-mail" required><br>
<textarea id="message" name="message" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio" required></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
<div id="alert">The fields are required! <button>OK</button></div>
This is overruling the default behavior in the browser. In any case I think the required attribute is the right way to go.
You may like to do something like this with your function:
function showAlerts(){
var allInputs = document.querySelectorAll('#name, #email, #message');
if(null != allInputs){
for(var i in allInputs){
if(!isNaN(i)){
// here you can check for values, emptiness etc
if(allInputs[i].value.trim() === ''){
// this field is empty
alert('This field is required!');
}
...
}
}
}
}
I am trying to validate a form using jquery form validator plugin. I want to display custom messages like if the email is not given then it should display email address is required, if email value is not a valid one then it should display invalid email address. But in both cases, it is giving me the same default message like 'You have not given a correct e-mail address'. I tried to like this
<form action="" id="registration-form">
<p>E-mail
<input name="email" id="email" data-validation="email" >
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
The script is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.20/jquery.form-validator.min.js"></script>
$.validate({
onElementValidate : function(valid, $el, $form, errorMess) {
if ($el.attr('name') == 'email') {
alert('Input ' +$el.attr('name')+ ' is ' + ( valid ? 'VALID':'NOT VALID') );
var value = $('#email').val();
if (value) {
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (! filter.test(value)) {
alert('invalid');
errorMess = 'invalid email';
}
} else {
alert('no mail');
errorMess = 'no email';
}
}
alert('errorMess :: ' + errorMess);
$('.help-block form-error').html(errorMess);
},
borderColorOnError: '#b94a48',
errorMessagePosition : 'inline',
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
It is pretty simple, adding multiple values in data-validation will actually done the magic.
<input name="email" id="email" data-validation="required, email" >
Is there a way to simplify my javascript code below?
It works but I am quite sure that there must be a way to reduce what evidently shows my elementary javascript skills, and of course, I am trying to improve my understanding.
My HTML Code is just a simple form:
<div>
<form action="">
<input type="text" name="firstname" id="un1" value="First Name"/>
<input type="text" name="surname" id="un2" value="Surname" />
<input type="text" name="username" id="un3" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
My Javascript Code (unobtrusive):
window.onload = function(){
//Field Manoeuvre1
document.getElementById("un1").onclick = fieldClear1;
document.getElementById("un1").onfocus = fieldClear1;
document.getElementById("un1").onblur = fieldReplace1;
//Field Manoeuvre2
document.getElementById("un2").onclick = fieldClear2;
document.getElementById("un2").onfocus = fieldClear2;
document.getElementById("un2").onblur = fieldReplace2;
//Field Manoeuvre3
document.getElementById("un3").onclick = fieldClear3;
document.getElementById("un3").onfocus = fieldClear3;
document.getElementById("un3").onblur = fieldReplace3;
}
//Field Manoeuvre1
function fieldClear1(){
if(document.getElementById("un1").value == "First Name"){
document.getElementById("un1").value = "";
}
}
function fieldReplace1(){
if(document.getElementById("un1").value == ""){
document.getElementById("un1").value = "First Name";
}
}
//Field Manoeuvre2
function fieldClear2(){
if(document.getElementById("un2").value == "Surname"){
document.getElementById("un2").value = "";
}
}
function fieldReplace2(){
if(document.getElementById("un2").value == ""){
document.getElementById("un2").value = "Surname";
}
}
//Field Manoeuvre3
function fieldClear3(){
if(document.getElementById("un3").value == "Email Address"){
document.getElementById("un3").value = "";
}
function fieldReplace3(){
if(document.getElementById("un3").value == ""){
document.getElementById("un3").value = "Email Address";
}
}
SOLUTION 1:
HTML:
<div>
<form action="">
<input type="text" name="firstname" id="un1" class="myInput" value="First Name"/>
<input type="text" name="surname" id="un2" class="myInput" value="Surname" />
<input type="text" name="username" id="un3" class="myInput" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
JS:
var defaultValues = {
un1 : 'First Name',
un2 : 'Surname',
un3 : 'Email Address'
}
var elements = document.querySelectorAll('.myInput');
for (var i=0; i<elements.length; i++) {
elements[i].addEventListener(['click', 'focus'], function(){
if (this.value === defaultValues[this.id]) this.value = '';
});
elements[i].addEventListener('blur', function(){
if (this.value === '') this.value = defaultValues[this.id];
});
}
PS: The code is not compatible with all browsers. If you aim for browser compatibility, you should probably use a library that abstracts away the differences (ex: jQuery).
SOLUTION 2:
No change in HTML
JS:
window.onload = function(){
var field;
//Field Manoeuvre1
field = document.getElementById('un1');
field.onclick = fieldClear.bind(field, 'First Name');
field.onfocus = fieldClear.bind(field, 'First Name');
field.onblur = fieldReplace.bind(field, 'First Name');
//Field Manoeuvre2
field = document.getElementById('un2');
field.onclick = fieldClear.bind(field, 'Surname');
field.onfocus = fieldClear.bind(field, 'Surname');
field.onblur = fieldReplace.bind(field, 'Surname');
//Field Manoeuvre3
field = document.getElementById('un3');
field.onclick = fieldClear.bind(field, 'Last Name');
field.onfocus = fieldClear.bind(field, 'Last Name');
field.onblur = fieldReplace.bind(field, 'Last Name');
}
function fieldClear(value){
if(this.value === value) this.value = '';
}
function fieldReplace(value){
if(this.value === '') this.value = value;
}
DEMO: http://jsbin.com/ekoJuQE/1/edit
Use either jquery or html5
Html5 solution:
Add parameter placeholder to input like this
<input name="firstname" type="text" placeholder="First name" />
Jquery (plus attribute data-placeholder="text shown in field" on html input fields:
$(window).on("load", function(){
$("#un1, #un2, #un3").on("click, focus", fieldClear(this));
$("#un1, #un2, #un3").on("blur", fieldReplace(this));
});
function fieldClear(obj) {
$(obj).val('');
}
function fieldReplace(obj) {
$(obj).val($(obj).data('placeholder'));
}
Delegated event handling can shorten things up a bit. If you pick up jQuery, then add classes or select by element type. Also add a data attr.
<input type="text" name="surname" id="un2" value="Surname" data-placeholder="Surname"/>
$('form').on('click, focus', 'input', function(e){
$(this).val("");
});
$('form').on('blur', 'input', function(){
$(this).val($(this).attr('data-placeholder'));
});
I'd like to create a webpage where the user can add and remove sets of form fields by means of one add button and remove buttons related to the set to be removed. Entered values will be checked by means jquery validate, for which rules are added dynamically as well. pls see an an simplified example below of my targeted form:
What is a good structure of javascript code for adding, removing and validate sets of forms fields? I googled -also on this site- and there are many javascript examples for adding sets of formfields. I like the example I found at view-source:http://www.coldfusionjedi.com/demos/jqueryvalidation/testadd.cfm, which uses a form template. But I struggle in particular with the javascript coding for the removing buttons..(which are not in the example)
my targeted (simplified) form (template with 1 set of 3 formfields):
<form name="myForm" id="myForm" method="post" action="">
<input id="name1" name="name1" />
<input id="email1" name="email1" />
<input id="phone1" name="phone1" />
<input type="submit" value="Save">
</form>
I think that you should template the form. I.e. wrap it in a function, so you can create it again and again. Here is a jsfiddle http://jsfiddle.net/krasimir/2sZsx/4/
HTML
<div id="wrapper"></div>
add form
JS
var wrapper = $("#wrapper");
var addForm = $("#add-form");
var index = 0;
var getForm = function(index, action) {
return $('\
<form name="myForm" id="myForm" method="post" action="' + action + '">\
<input id="name' + index + '" name="name' + index + '" />\
<input id="email' + index + '" name="email' + index + '" />\
<input id="phone' + index + '" name="phone' + index + '" />\
<input type="submit" value="Save">\
remove form\
</form>\
');
}
addForm.on("click", function() {
var form = getForm(++index);
form.find(".remove").on("click", function() {
$(this).parent().remove();
});
wrapper.append(form);
});
Simple validation can be done when your form is submitted, thus:
$('#myForm').submit({
var n1 = $('#name1').val();
var e1 = $('#email1').val();
var p1 = $('#phone1').val();
if (n1=='' || e1=='' || p1=='') {
alert('Please complete all fields');
return false;
}
});
Note that the return false will abort the submit and return user to the document.
Great code for adding/removing form fields can be found in this question: https://stackoverflow.com/questions/18520384/removing-dynamically-generated-textboxes-in-jquery
jsFiddle here
If you are using KeenThemes (maybe Metronic theme)
https://preview.keenthemes.com/good/documentation/forms/formvalidation/advanced.html
You can do like this.
var form = document.getElementById('form_id');
var validator = FormValidation.formValidation(
form,
{
fields: {
name: {
validators: {
notEmpty: {
message: 'Please enter template name'
},
stringLength: {
min: 3,
trim: true,
message: 'Please enter a longer name.'
},
}
},
...
more fields here
...
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap: new FormValidation.plugins.Bootstrap(),
},
});
function addNewFieldDynamically() {
// add new field here
...
validator.addField('field_name', {
validators : {...}
})
}
function removeFieldDynamically() {
// remove a field here
...
validator.removeField('field_name')
}
Required field custom validation
I have one form with many input fields. I have put html5 validations
<input type="text" name="topicName" id="topicName" required />
when I submit the form without filling this textbox it shows default message like
"Please fill out this field"
Can anyone please help me to edit this message?
I have a javascript code to edit it, but it's not working
$(document).ready(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter Room Topic Title");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
Email custom validations
I have following HTML form
<form id="myform">
<input id="email" name="email" type="email" />
<input type="submit" />
</form>
Validation messages I want like.
Required field: Please Enter Email Address
Wrong Email: 'testing#.com' is not a Valid Email Address. (here, entered email address displayed in textbox)
I have tried this.
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("'" + input.value + "' is not a Valid Email Address.");
}
else {
input.setCustomValidity("");
}
}
This function is not working properly, Do you have any other way to do this? It would be appreciated.
Code snippet
Since this answer got very much attention, here is a nice configurable snippet I came up with:
/**
* #author ComFreek <https://stackoverflow.com/users/603003/comfreek>
* #link https://stackoverflow.com/a/16069817/603003
* #license MIT 2013-2015 ComFreek
* #license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
* You MUST retain this license header!
*/
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}
function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));
function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}
function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}
input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);
Usage
→ jsFiddle
<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
defaultText: "Please enter an email address!",
emptyText: "Please enter an email address!",
invalidText: function (input) {
return 'The email address "' + input.value + '" is invalid!';
}
});
More details
defaultText is displayed initially
emptyText is displayed when the input is empty (was cleared)
invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)
You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.
Compatibility
Tested in:
Chrome Canary 47.0.2
IE 11
Microsoft Edge (using the up-to-date version as of 28/08/2015)
Firefox 40.0.3
Opera 31.0
Old answer
You can see the old revision here: https://stackoverflow.com/revisions/16069817/6
You can simply achieve this using oninvalid attribute,
checkout this demo code
<form>
<input type="email" pattern="[^#]*#[^#]" required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit"/>
</form>
Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP
HTML:
<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" type="email" required="required" />
<input type="submit" />
</form>
JAVASCRIPT :
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;
}
Demo :
http://jsfiddle.net/patelriki13/Sqq8e/
Try this:
$(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("Please enter Room Topic Title");
};
}
})
I tested this in Chrome and FF and it worked in both browsers.
Man, I never have done that in HTML 5 but I'll try. Take a look on this fiddle.
I have used some jQuery, HTML5 native events and properties and a custom attribute on input tag(this may cause problem if you try to validade your code). I didn't tested in all browsers but I think it may work.
This is the field validation JavaScript code with jQuery:
$(document).ready(function()
{
$('input[required], input[required="required"]').each(function(i, e)
{
e.oninput = function(el)
{
el.target.setCustomValidity("");
if (el.target.type == "email")
{
if (el.target.validity.patternMismatch)
{
el.target.setCustomValidity("E-mail format invalid.");
if (el.target.validity.typeMismatch)
{
el.target.setCustomValidity("An e-mail address must be given.");
}
}
}
};
e.oninvalid = function(el)
{
el.target.setCustomValidity(!el.target.validity.valid ? e.attributes.requiredmessage.value : "");
};
});
});
Nice. Here is the simple form html:
<form method="post" action="" id="validation">
<input type="text" id="name" name="name" required="required" requiredmessage="Name is required." />
<input type="email" id="email" name="email" required="required" requiredmessage="A valid E-mail address is required." pattern="^[a-zA-Z0-9_.-]+#[a-zA-Z0-9-]+.[a-zA-Z0-9]+$" />
<input type="submit" value="Send it!" />
</form>
The attribute requiredmessage is the custom attribute I talked about. You can set your message for each required field there cause jQuery will get from it when it will display the error message. You don't have to set each field right on JavaScript, jQuery does it for you. That regex seems to be fine(at least it block your testing#.com! haha)
As you can see on fiddle, I make an extra validation of submit form event(this goes on document.ready too):
$("#validation").on("submit", function(e)
{
for (var i = 0; i < e.target.length; i++)
{
if (!e.target[i].validity.valid)
{
window.alert(e.target.attributes.requiredmessage.value);
e.target.focus();
return false;
}
}
});
I hope this works or helps you in anyway.
This works well for me:
jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});
and the form I'm using it with (truncated):
<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>
You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.
[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
emailElement.addEventListener('invalid', function() {
var message = this.value + 'is not a valid email address';
emailElement.setCustomValidity(message)
}, false);
emailElement.addEventListener('input', function() {
try{emailElement.setCustomValidity('')}catch(e){}
}, false);
});
The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.
Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.
Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/
Hope that helps!
Just need to get the element and use the method setCustomValidity.
Example
var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');
Use the attribute "title" in every input tag and write a message on it
you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() eventListener!
Here is my demo codes!(you can run it to check out!)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oninvalid</title>
</head>
<body>
<form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >
<input type="email" placeholder="xgqfrms#email.xyz" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
<input type="submit" value="Submit">
</form>
</body>
</html>
reference link
http://caniuse.com/#feat=form-validation
https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation
You can add this script for showing your own message.
<script>
input = document.getElementById("topicName");
input.addEventListener('invalid', function (e) {
if(input.validity.valueMissing)
{
e.target.setCustomValidity("Please enter topic name");
}
//To Remove the sticky error message at end write
input.addEventListener('input', function (e) {
e.target.setCustomValidity('');
});
});
</script>
For other validation like pattern mismatch you can add addtional if else condition
like
else if (input.validity.patternMismatch)
{
e.target.setCustomValidity("Your Message");
}
there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid
use it on the onvalid attribute as follows
oninvalid="this.setCustomValidity('Special Characters are not allowed')