HTML5 Form validation - error message customization - javascript

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

Related

Onfocusout problems

I have a JavaScript function that is triggered when the onfocusout attribute of an input field is called, which works perfectly.
The only problem I have is that at the first time, whenever the user inputs a text, after executing the JavaScript function, the value of the input disappears from the screen, so the user has to input it a second time.
How can I solve this?
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" onfocusout="passcheck(0)" title="input must not be less than 8 characters" required></input>
function passcheck(type){
var status=false;
switch(type) {
case 1:
var divP=document.getElementById("form-group password");
if(!document.getElementById("passHelp"))
divP.innerHTML+="<small id='passHelp' hidden class='form-text text-muted' color='red'>Password mismatch.</small>";
if(!status){ document.getElementById("passHelp").hidden=false;
document.getElementById("passHelp").style.color="Red";
}
else{ document.getElementById("passHelp").hidden=true; }
break;}
return status; }

How to force validate data of the HTML 5 input from jquery?

I do have a input with the pattern and the title to show the error in case of wrong data, I do need to not use the post method, so I just make some Jquery code to use the input validation, but I can't find how to show the default message of the input
This is the HTML5 input:
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
And this is the jquery code:
$("#inputEnviar").click(
function(){
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if ( userValidation ){
//code to do whatever I have to do if the data is valid
} else {
//if the data is invalid
//the input already has a default message to show
//then, how do I force to show
$("#user")-> FORCE TO SHOW TO THE DEFAULT ERROR MESSAGE OF THE INPUT
}
});
If the validation fails, in your else code block, set the custom message that you want to notify to the user:
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
Then, you can use reportValidity() to show that message. From MDN:
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
$("#inputEnviar").click(
function() {
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if (userValidation) {
//code to do whatever I have to do if the data is valid
} else {
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
var isValid = $('#user')[0].reportValidity();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
<input id="inputEnviar" type="button" value="Send">
For old browsers (i.e. IE) you would need to use a polyfill.
There are several implementations around (like this git). This article goes deeper on the topic.
This should work. The reportValidity() function will show the default message after you have set it with setCustomValidity.
function send() {
var input = $("#user")[0];
input.setCustomValidity("");
if(!input.checkValidity()) {
input.setCustomValidity("watch me break");
input.reportValidity();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" pattern="[^,]*" title="Message">
<button onclick="send()">Click</button>

Javascript disable input field

I have two input fields one is for a phone number another is for an email. I would like to disable one field based on the user selection. Should a user click and enter input in either field, it would disable the other and vice versa.
I have written code but it seems to only disable the email field upon entering in numbers in the phone field. Removing the numbers in the phone field removes the disabled from the email input field.
IN MY HTML
<input type="number" name="number" placeholder="hone" class="cellphone" data-cp-visibility="new-user" id="phone">
<input type="email" name="email" placeholder="enter email" class="email" data-cp-visibility="new-user" id="email">
IN JAVASCRIPT
$('#phone').live('blur',function(){
if(document.getElementById('phone').value > 1) {
$('#email').attr('disabled', true);
} else {
$('#email').attr('disabled', false);
}
});
$('#email').live('blur',function(){
if(document.getElementById('email').value > 1) {
$('#phone').attr('disabled', true);
} else {
$('#phone').attr('disabled', false);
}
});
Ultimately I what I am trying to accomplish is that a user can click in either field and then enter input, upon doing so, the other field is disabled. Should they choose to remove the text they entered, it would remove the disabled feature and then they could choose the opposite input field.
I am not sure why it only works for one field and not the other or why if you enter in 333-333-3333 in the phone field it breaks the disabled, but 33333333 works fine.
Any ideas or insight as to what I may be missing?
to fix the dash issue you are having with the phone input, you can try changing it to:
<input type="text" required="" pattern="\d{3}[\-]\d{3}[\-]\d{4}" name="phone" id="phone" data-cp-visibility="new-user" placeholder="123-345-5678">
and here is another version of the js:
var $phone = $('#phone'),
$email = $('#email');
$phone.on('keyup change', function() {
$email.prop('disabled', $(this).val() ? true : false );
});
$email.on('keyup change', function() {
$phone.prop('disabled', $(this).val() ? true : false );
});
You may use jQuery on instead of live. live is deprecated as of jQuery 1.7.
You can also look for the keyup/keydown event on the input element.
$(function(){
$('#phone').on('keyup',function(){
if($(this).val()!=="")
{
$('#email').prop('disabled', true);
}
else {
$('#email').attr('disabled', false);
}
});
$('#email').on('keyup',function(){
if($(this).val()!=="")
{
$('#phone').prop('disabled', true);
}
else {
$('#phone').prop('disabled', false);
}
});
});
Here is a working sample.
I would recommend using .on('input', ...) to listen for changes, this makes it so even if you use the increment/decrement buttons (or other forms of input) you'll trigger the event-handler. Then use .attr('disabled', boolean) to control enable/disabled state, see example below:
$(function() {
$('#phone').on('input', function() {
$('#email').attr('disabled', $(this).val() !== "");
});
$('#email').on('input', function() {
$('#phone').attr('disabled', $(this).val() !== "");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" placeholder="phone" id="phone">
<input type="email" placeholder="enter email" id="email">

Validating form data in Javascript xhtml 1.0 strict, not considering server side scripts for this instance

There are other questions regarding validating email addresses with javascript. There are also questions regarding validating forms. However I cannot get my code to work, and cannot find a question to cover this particular issue.
Edit
I totally understand that in a live website, server side validation is vital. I also understand the value of sending email confirmation. (I actually have a site that has all these features). I know how to code spam checks in php.
In this instance I have been asked to validate the email input field. I have to conform to xhtml 1.0 strict, so cannot use the type "email", and I am not allowed to use server side scripts for this assignment. I cannot organise email confirmation, it has to be totally checked via javascript.
I hope this clarifies my question
I am trying to validate a form for two things.
To check that all fields have data.
To see if a valid email address is entered.
I am able to validate a form fields for data, but trying to incorporate the email check is a trouble for me.
It was giving alerts before, but incorrectly, now it is not being called at all (or at least that is how it is behaving).
Once I get this working I then need to focus on checking if the email addresses match. However this is an issue outside of this question.
I am only focused on validating this in javascript. I am not concerned about server side in this particular instance (another issue outside of this question). Thanks.
function Validate()
{
var inputs = [document.getElementById('fname'),_
document.getElementById('lname'), document.getElementById('email1'),_
document.getElementById('email2')];
for(var i = 0; i<inputs.length; i++)
{
if(inputs[i].value == '')
{
alert('Please complete all required fields.');
return false;
}
else if ((id =='email1' || 'email2') &&_
(inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}
}
}
<form onsubmit="return Validate()" action="" method="post" id="contactForm" >
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" name="email1" id="email1" />
<input type="text" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>
A side note - to format text that wraps, is it ok (for the purposes of posting a question, to add and underscore and create a new line for readability? In the actual text I have it doesn't have this! Please advise if there is a simpler way to format my code for posts. Thanks again.
Edit 2
It works when I comment out this:
/*else if ((id =='email1' || id=='email2') && (inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}*/
So this helps with the trouble shooting.
I already see a syntax error there :
else if ((id =='email1' || 'email2')
should be
else if ((id =='email1' || id=='email2')
from where I see it.
Note also that entering a space in any field will also pass through the test : you should trim your field values when testing for empty ones.
finally, concerning validating the email, this is not how you use regex. Please read this post for a demonstration on how to validate an email in javascript+regex.
var a=document.getElementById('fname');
var b=document.getElementById('lname');
var c=document.getElementById('email1');
var d=document.getElementById('email12')
if(a==""||b==""||c==""||d=="")
{
alert('Please complete all required fields.');
return false;
}
The best thing to do with validating an email address is to send an email to the address. Regex just doesn't work for validating email addresses. You may be able to validate normal ones such as john.doe#email.com but there are other valid email addresses you will reject if you use regex
Check out Regexp recognition of email address hard?
AND: Using a regular expression to validate an email address
I worked out the solution to my problem as follows. I also have in here a check to see if emails match.
// JavaScript Document
//contact form function
function ValidateInputs(){
/*check that fields have data*/
// create array containing textbox elements
var inputs = [document.getElementById("fname"),_
document.getElementById("lname"), document.getElementById("message"),_
document.getElementById("email1"), document.getElementById("email2")];
for(var i = 0; i<inputs.length; i++){
// loop through each element to see if value is empty
if(inputs[i].value == ""){
alert("Please complete all fields.");
return false;
}
else if ((email1.value!="") && (ValidateEmail(email1)==false)){
return false;
}
else if ((email2.value!="") && (EmailCheck(email2)==false)){
return false;
}
}
}
function ValidateEmail(email1){
/*check for valid email format*/
var reg =/^.+#.+$/;
if (reg.test(email1.value)==false){
alert("Please enter a valid email address.");
return false;
}
}
function EmailCheck(email2){
var email1 = document.getElementById("email1");
var email2 = document.getElementById("email2");
if ((email2.value)!=(email1.value)){
alert("Emails addresses do not match.");
return false;
}
}
<form onsubmit="return ValidateInputs();" method="post" id="contactForm">
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" onblur="return ValidateEmail(this);" name="email1" id="email1" />
<input type="text" onblur="return EmailCheck(this);" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>

Customizing the message in a jQuery validate custom rule

I have a custom jQuery validate rule called fiftyCents() where there are two rules:
if the item is free, one can "buy" it for $0.00 or they can pay greater than $0.50.
if the item is NOT free, then they must pay at least the cost specified (stored in a hidden cachedValue input field).
So those are my two validation error messages. The problem I'm having in adding these to fiftyCents() is that I can only figure out how to evaluate it as true/false and if false, display a single message, e.g., "Amount must be $0.00 OR greater than $0.50.".
The solution to the JSfiddle (code below too) appears to be to make a message object that could be part of the fiftyCents() function. However, I don't know how to return that along with evaluating true/false. Thoughts?
JS:
$('button').click(function(){
$('form').validate().form();
});
$.validator.addMethod("fiftyCents", function(value) {
var cachedValue=$('.purchaseModalAmtPaidCached').val();
var value = $('.purchaseModalAmtPaid').val();
var message="Amount must be $0.00 OR greater than $0.50.";
if(cachedValue>0) message='Amount must be at least'+cachedValue+'.';
return cachedValue<=value && (value==0 || (0.51<=value && value<=10000));
}, message);
$.validator.classRuleSettings.purchaseModalAmtPaid = { fiftyCents: true };
HTML:
<form>
<input class="purchaseModalPassword required" minlength="8" type="password"name="password" value="dddddddv" title="Please enter a valid password" />
<input type="text" title="Amount must be $0.00 OR greater than $0.50"
class="required purchaseModalAmtPaid" name="amt_paid" value="" />
<input type="hidden" class='purchaseModalAmtPaidCached required' name="AmtPaidCached" value="0.00" />
<button type='button'>Buy</button>
</form>​
Ok I answered my own question. What I ended up doing is splitting up the two rules into their own custom methods. I used an if/else before either custom method is invoked to determine which of the two should be followed.
Here's the JSFiddle and code below:
JS:
$('button').click(function(){
$('form').validate().form();
});
var params=$('.purchaseModalAmtPaidCached').val();
if(params>0){
$.validator.addMethod("AmountOrGreater", function(value, element, params) {
console.log('amountOrGreater'+params[0]);
return params[0]<=value && (value==0 || (0.51<=value && value<=10000));
}, $.validator.format("Amount must be at least {0}."));
$.validator.classRuleSettings.purchaseModalAmtPaid = { AmountOrGreater: params };
}
else{
$.validator.addMethod("fiftyCents", function(value, element, params) {
console.log('fiftyCents'+params[0]);
return params[0]<=value && (value==0 || (0.51<=value && value<=10000));
}, "Amount must be $0.00 OR greater than $0.50.");
$.validator.classRuleSettings.purchaseModalAmtPaid = { fiftyCents: params };
} //else
HTML:
<form>
<input class="purchaseModalPassword required" minlength="8" type="password" name="password" value="dddddddv" title="Please enter a valid password" />
<input type="text"
class="required purchaseModalAmtPaid" name="amt_paid" value="" />
<input type="hidden" class='purchaseModalAmtPaidCached required' name="AmtPaidCached" value="0.00" />
<button type='button'>Buy</button>
</form>​
Note: A key to the HTML cooperating with jQuery validate is that if you give your inputs a title='' attribute then that title will always be used, thus overriding the message in your custom rule. This is relevant in my case b/c there were two custom rules/messages and I'm not able to determine in advance of the HTML being rendered which one the user would see.

Categories