jquery form validation using groups - javascript

I have an order form, one part of the form is the address. It contains Company, Street-Address, ZIP, Town, Country with a simple jquery form validation with every field required, and ZIP validated for number. Now what I want is to group them and only have one field showing "valid address" on success, or "address wrong" on error.
This is a part of my js code:
$("#pageform").validate(
{
messages: {
company_from: addressError, //addressError is a JS var for the error message
street_from: addressError,
zip_from: addressError,
town_from: addressError,
country_from: addressError
},
groups: {
from: "company_from street_from zip_from town_from country_from"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "company_from"
|| element.attr("name") == "street_from"
|| element.attr("name") == "zip_from"
|| element.attr("name") == "town_from"
|| element.attr("name") == "country_from"
)
{
$("#error_from").append(error);
}
},
success: function(label) {
var attribute = $(label[0]).attr("for");
$(".err-ok-" + attribute + " .ok").css("display", "block").css("visibility", "visible");
}
}
);
This is a part of the corresponding HTML code:
<input type="text" name="company_from" id="company_from" class="required default input-s8" maxlength="255" />
<input type="text" name="street_from" id="street_from" class="required default input-s8" maxlength="255" />
<input type="text" name="zip_from" id="zip_from" class="required digits default input-s8" maxlength="5" onblur="checkCalculation()" />
<input type="text" name="town_from" id="town_from" class="required default input-s8" maxlength="255" />
<!-- and a select list for the country -->
You do not need to take a closer look on how I show the error and so on, my problem is, that I do not know when to show the error label and when the success label. When I enter a letter for the ZIP code, my errorPlacement function and the success function is called (and the errorPlacement first), so I guess it's always calling the success if there is at least one field correct.
Please ask if there are any questions, and I am pretty sure there are... :-)

Add rules
rules: {
company_from: "required",
company_from: "required",
zip_from: "required",
town_from:"required",
country_from:"required"
},

Related

Multiple language validation handling logic

I've a form with multiple languages eg: English, German, Chineese.
Each one contains three fields-
select list
heading textbox
textarea
completed the validation based on everything is mandatory logic.
My requirement has been changed now,
If user directly hit submit button without filling feilds everything should be highlighted.
If user add a field value of any of the lang, remaining blank fields of respective lang should be highlighted
eg: User added German heading value, remaining two fields of german only highlighted
Thanks in advance ;)
You can use depend function in jquery
How to use jquery validate "depends" on rules other than "required"?
<input type="text" name="text1" id="text1" class="form-control frm1">
<input type="text" name="text2" id="text2" class="form-control frm1">
<input type="text" name="text3" id="text3" class="form-control frm1">
In your jquery validation
text1: {
required: {
depends: function(element) {
return ($("#text2").val() == "" || $("#text3").val() == "" );
}
},
},
text2: {
required: {
depends: function(element) {
return ($("#text1").val() == "" || $("#text3").val() == "" );
}
},
},
text3: {
required: {
depends: function(element) {
return ($("#text1").val() == "" || $("#text2").val() == "" );
}
},
}
Hope now you understand something,

Javascript validation nightmare

I'm trying to get my "username" and "password" fields to verify that there is information in them before submitting the form.
What should I need to add to my HTML and to my JavaScript to have them work! If you want to suggest a new JavaScript, please do!
HTML:
<form action="validateForm.html" id="registrationForm">
<label for="username" id="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" value="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" id="passwordLabel">* Password:</label>
<input type="password" name="password" id="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" id="submit" />
</form>
JavaScript
function validateForm()
{
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
if(!document.forms[0].username){
alert("Username field is required!");
}
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
}
One way would be getting your input by id and then validate its value
HTML
<input type="text" id="username" />
<input type="password" id="password" />
JS
function validateForm()
{
if(!document.getElementById("username").value) // true if input value is null, undefined or ""
{
alert("Username field is required!");
}
else if(!document.getElementById("password").value)
{
alert("Username field is required!");
}
}
(i strongly recommend you to use more attractive ways of giving users feedback than JS alerts)
I think all of those checks are incorrect in some for, let's start with the first one:
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
It's document.getElementsByName() (notice the plural)
The function returns an array of elements, so you'd still need to check for the value of the one you want (probably 0)
This is going to be true always as the field exist, you need to check the value in the input, but right now you are just checking the existence of the input.
Next one is similar:
if(!document.forms[0].username){
alert("Username field is required!");
}
You are checking the existence of the field, not its value
This type of selection is not recommended, you should be using a document.getElementBy... better.
And finally:
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
It looks like you tried to make a for loop but copy-pasted from above and got this mess... not even going to try to understand why the loop.
Recommendations:
Use the attribute id and read the fields using document.getElementById()
To check if a field has content, check its value: .value
Add an event handler for the form (onsubmit="validateForm()")
Make the form validator return false if one of the fields is incorrect (otherwise the form will be sent even with the incorrect fields)
Optionally: use the HTML5 required attribute.
So the function would look like:
function validateForm()
{
if(document.getElementById("username").value == "")
{
alert("Username field is required!");
return false;
}
// check the other fields
// .....
}
May I suggest something like this instead:
HTML:
<form action="validateForm.html" onSubmit="return validateForm(this)">
<label for="username" name="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" placeholder="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" name="passwordLabel">* Password:</label>
<input type="password" name="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" />
</form>
JS:
function isEmpty (field) {
return field.value === "";
}
function validateForm (form) {
// assume the form to be valid
var isValid = true;
// create a variable to store any errors
var errors = "";
// check if the username is empty
if(isEmpty(form.username)) {
// our assumption is incorrect, the form is invalid
isValid = false;
// append the error message to the string
errors += "Username field is required!\n";
}
if (isEmpty(form.password)) {
isValid = false;
errors += "Password field is required!\n";
}
// display the errors if the form is invalid
if (!isValid) {
alert(errors);
}
return isValid;
}
This way, you are passing the form directly to the validateForm function and can easily access each field using their name properties. You can then check if they're empty by determining what their value contains.
If you need to get the DOM by it name means it will returns an Array so you need to get it by
if(!document.getElementsByName("username")[0].value == ""){
//do ur stuff
}
or
if(!document.getElementById("username").value == ""){
//do ur stuff
}

Show hide div and script based on radio button

I'm trying to implement validation into my form being conditional. Basically if the user selects email radio option then email is going to be required, or if phone is selected then phone field would be required.
So far I've gotten this code to work, form submits and validation works fine. But if I switch to phone, then switch back to email, the validation is loaded so form won't submit if I haven't filled out both fields.
I have it set that way but basically trying to make it so if one field is selected then the other required. Any better ways to do this?
HTML:
<label>Method of Contact</label>
<label class="radio">
<input type="radio" name="group" value="ck1" checked/>
Email
</label><br />
<label class="radio"><input type="radio" name="group" value="ck2" />
Phone
</label>
<div id="emaildisp">
<label>Email</label>
<input id="emailv" name="email" type="email" />
</div>
<div id="phonedisp">
<label>Phone</label>
<input id="phonev" name="phone" type="text" />
</div>
Javascript:
$(function()
{
if (jQuery('input[value=ck2]:checked').length > 0)
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
jQuery('input[name=group]').change(function()
{
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2')
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
});
Solution:
Thanks to the answers below, I came up with the solution. Key difference, I was not using jquery validation plugin, rather a different validation script. So I switched over, for beginners, just look it up you'll simply have to add link to the script in the header.
Next I gave the form an id, #myform. Then I have the ck1 and ck2 radio button their own respective ids, #ck1id and #ck2id. And using the below code, if the radio button is selected, then depending on the id selected, next part becomes validation required.
<script type='text/javascript'>
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
}
});
jQuery('input[name=group]').triggerHandler('change');
});
</script>
<script>
$(function(){
// validate signup form on keyup and submit
$("#myform").validate({
rules: {
group: "required",
email:
{
required: '#ck1id:checked',
email: true
},
phone:
{
required: '#ck2id:checked',
digits: true
}
},
messages: {
group: "Please select one",
email: "Please enter your email.",
phone: "Please enter your phone."
}
});
});
</script>
You need to remove the previously added validation from the other fields those are not required. If you need phone remove validation from email and vice versa.
You can follow two way, either remove validation or ignore the validation.
1. Removing the validation:
jQuery("#emailv").rules('remove');
or
jQuery("#phonev").rules('remove');
2. Ignore validation:
jQuery("#emailv").validate({
ignore: "#emailv"
});
or
jQuery("#phonev").validate({
ignore: "#phonev"
});
Check if this helps you.
Use .rules("remove") to remove jquery validation.
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#emailv").rules("remove"); //remove the other field validation
jQuery("#phonev").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#phonev").rules("remove"); //remove the other field validation
jQuery("#emailv").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
jQuery('input[name=group]').triggerHandler("change");
});
I see that you have duplicated code, just remove it and use jQuery('input[name=group]').triggerHandler("change"); to trigger it when page first loads

Set custom HTML5 required field validation message

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')

Figuring out form validation to validate a value across multiple inputs

I'm using the jQuery form wizard plugin. I have 20 questions that each have three answers. Each answer can have a weight. For each question, the total weight of the answers must be equal to 10.
<fieldset id="first" class="step">
<input type="text" size="2" maxlength="2" value="" name="question1[]" class="required"/>A: Inspiring others with a compelling vision for change.<br />
<input type="text" size="2" maxlength="2" value="" name="question1[]" />B: Engaging others to buy-into the change.<br />
<input type="text" size="2" maxlength="2" value="" name="question1[]" />C: Executing a project plan and managing accountabilities.<br />
<label for="question1[]" class="error" style="display:none;">Your values must add up to 10!</label>
</fieldset>
This is basically a personality assessment. Let's say I feel A and C do not apply, I'd enter in 10 for A.
Is there any way to check to see if each field set is adding up to 10 and if not send an error message?
I am using the jQuery validation plugin, but this seems to be a bit too specific, as I know it checks for numbers, etc.
I've tried to add something along the following to even get a required check to pass, but I'm not sure where to go from here:
$(document).ready(function() {
$("#Form").validate({
submitHandler: function(form) {
form.submit();
}
});
$("#Form input[name='question1']").each(function() {
$(this).rules("add", {
required: true,
maxlength: 2,
messages: {
required: "Required",
minlength: jQuery.format("Max length of {2} characters.")
}
});
});
});
I have also found that jQuery validate had to have a function edited to accomodate arrays. I've changed the following function:
checkForm: function() {
this.prepareForm();
for (var i=0, elements=(this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName(elements[i].name).length != undefined &&
this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
}
else {
this.check( elements[i] );
}
}
return this.valid();
}
I have also tried this:
$(document).ready(function(){
$("#Form").validate({
rules: {
question1: {
required: true
}
},
submitHandler: function(form) {
form.submit();
}
});
});
None of this seems to work to even give me a 'required' error. There are no errors in console. I need to validate this on each question as the "next" button is pressed. The next button does have type=submit, so it theoretically should at least see that I said question 1 must be required but to no avail.
I also tried this:
$().ready(function() {
// validate the comment form when it is submitted
$("#Form").validate({
rules: {
"question1[]": "required"
},
messages: {
"question1[]": "Input is required",
}
});
});
But it goes on to the next fieldset with no error.
In this case, create a new input that's disabled, and when the individual weight values change, change the value of this disabled input to be the sum. Validate the disabled input - require it's value be equal to 10, and if it's not, show an error.

Categories

Resources