How to give custom validation error messages for HTML validations? - javascript

When I use default HTML validation it shows the default error messages which is not I want to show to my clients. I need to customize the message and give different massages for each validations such as min, max, type and require. For Example:
The field is required, The value does not match
Refer the tradition HTML Code:
<input type="text" required>
I want something like this:
<input type="text" validation="required|my_message,min:5|my_message">

It's totally possible with custom libraries in jQuery which I would suggest - https://github.com/aslamanver/abvalidate
Custom Message - jQuery Form Validation - abValidate.js
ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name"
Use this library by adding these CDNs
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- abValidate Library -->
<script type="text/javascript" src="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.min.js">
<link rel="stylesheet" href="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.css">
Initialize the library
$(document).ready(function () {
//.ab-form is your form class
$(".ab-form").abValidate();
});
There you go, now you can use your custom validation using jQuery abValidate library
<form class="ab-form" action="your_action_url">
<!-- Input and error message should be in a div class -->
<div class="my-form-group">
<input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name" class="ab-validation-i" />
<div class="error"></div>
</div><br>
<div class="my-form-group">
<input type="submit" name="submit" value="Submit">
</div>
</form>

Try this one, its better and tested:
HTML:
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
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/

Related

the text-box does't change the color in javascript

First, Happy New Year everyone!
I tried make a Form in which the Check Boxes(text)at the start(calling a function, verif()) where they must be in different color than as soon the user input a name the Colors must change in white, also I use the method, setCustomValidity to advice the user to fill the box in a case he(she) forgot but even I don't get the error massage where I must fill the box.
Unfortunately my plan looks has error but I don't know where is that.
<section id="secty">
<h1 id="demo">Managing Form</h1>
<form id="usuer_register" name="usuer_register" method="post">
<table>
<tr><td>Name:</td>
<td><input type="text" id="nam" name="nam"></td></tr>
<tr><td>Last name:</td>
<td><input type="text" id="name1" name="name1"></td></tr>
<tr><td>Age:</td>
<td><input type="text" id="age" name="age"></td></tr>
<tr><td><input type="submit" id="regist" name="regist"></td></tr>
</table>
</form>
</section>
<script>
function start(){
var x=document.getElementById("nam");
var y=document.getElementById("name1");
x.addEventListener("input", verif, false);
y.addEventListener("input", verif, false);
verif();
}
function verif(){
if(x.value=="" && y.value==""){
x.setCustomValidity("Enter Name or Lastname");
x.style.background="#803ADD";
y.style.background="#803ADD";
}
else{
x.setCustomValidity(""); // this restart as default;
x.style.background="#FFFFFF";
y.style.background="#FFFFFF";
}
}
window.addEventListener("load", start, false);
</script>
There's a bunch here to re-work. Check the HTML, CSS, and JavaScript comments in the code below for details, but the main point is that HTML, CSS, and JavaScript already provide most of the functionality you are looking for. If you simply add required to the input elements that cannot be blank, you'll get automatic validity checking and styling.
Check our how HTML5 Form Validity works.
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<style>
/* CSS provides valid and invalid pseudo-classes which will automatically
kick in based on the validity of form elements */
.validate:valid { background-color:#fff; }
.validate:invalid { background-color:#803ADD; }
label { display:inline-block; width: 5em; }
form > div { margin-bottom: .2em; }
</style>
</head>
<body>
<section>
<h1>Managing Form</h1>
<!-- Don't forget to fill in the action attribute of the form! -->
<form id="usuer_register" name="usuer_register" method="post" action="">
<!-- Do not use tables for layout! They are only for displaying tabular data. -->
<div>
<!-- Use label elements with form fields for better accessibility.
Now, clicking on the label text focuses the field. Also, type="text"
is not required on textboxes as "text" is the default type.
Lastly, just add the "required" attribute for automatic validity checking. -->
<label for="fName">Name: </label><input id="fName" name="fName" class="validate" required>
</div>
<div>
<label for="lName">Last Name: </label><input id="lName" name="lName" class="validate" required>
</div>
<div>
<label for="age">Age: </label><input id="age" name="age">
</div>
<div>
<!-- Submit Buttons shouldn't have a name because they
don't have any data that you would want submitted
along with the form. -->
<input type="submit">
</div>
</form>
</section>
<!-- As long as your script element is the last element
in the body, there is no need for a "start" function
or a "load" event hander. The following code will just
run when it is reached and at this point in the document
all the HTML has been parsed. -->
<script>
// Use meaningfull variable names
let fName = document.getElementById("fName");
let lName = document.getElementById("lName")
// The inputs will be invalid initially, so flag them
// that way from the start
fName.setCustomValidity("Enter First Name");
lName.setCustomValidity("Enter Last Name");
fName.addEventListener("input", verif);
lName.addEventListener("input", verif);
function verif(){
// The field has recieved input, so the required validation
// requirement has been met.
this.setCustomValidity("");
}
</script>
</body>
</html>
Happy New Year!

On-blur in angular directive not working properly

I have created a form. I have two email fields one is for Email and the other is confirm Email.
I wanted to create a directive which will compare confirmEmail field and Email field on blur of ConfirmEmail field. And on blur of confirm email i wanted to validate and show message if it doesn't match with email field.
Doubt: I am almost done. But somehow the onblur is not behaving properly.
One of the below case:
When I enter a#x in email field. Then a#t in confirm email field and tab out. I see the validation message as it doesn't match.
After that when I go back to confirm email field and make a#xsdf and tab out the validation doesn't fire.But if I type in some other textbox in the form like firstname then message gets reflected. Could you please suggest what is wrong in the code.
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css">
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<title></title>
</head>
<form name="myForm" novalidate>
<div class="col-xs-12" ng-controller="myController">
<br>
<br> First Name
<br>
<firstname></firstname>
<div ng-if="myForm.txtFirstName.$dirty">
<div class="danger" ng-show="myForm.txtFirstName.$error.pattern">
Enter First Name without Special Character
</div>
</div>
<br>
<br> Last Name
<br>
<input type="text" ng-model="LastName" name="txtLastName" class="form-control"></input>
<br>
<br> Email
<br>
<input type="email" name="txtemail" ng-model="Email" class="form-control"></input>
<div ng-if="myForm.txtemail.$dirty">
<div class="danger" ng-show="myForm.txtemail.$invalid">
Enter Valid Email Id
</div>
</div>
<br>
<br> Confirm Email
<br>
<input type="text" name="txtConfirmEmail" ng-disabled="!myForm.txtemail.$viewValue"
ng-model="EmailConfirm" match match-Email="{{Email}}" match-Cemail="{{EmailConfirm}}" class="form-control"></input>
<div class="danger" ng-show="mismatch">
<span>Email and Confirm Email must match.</span>
</div>
</div>
</form>
</html>
https://plnkr.co/edit/Tn70GxyqAadg0EdqjFG6?p=preview
jquery events doesnt trigger $digest circle of angular, you should use $apply for trigger this circle
scope.mismatch = false;
debugger
if (attrs.matchEmail === attrs.matchCemail) {
scope.$apply(function(){
scope.mismatch = false
});
} else
scope.$apply(function(){
scope.mismatch = true
});
});
One way around is to replace {{Email}} with current form value:
<input type="text" name="txtConfirmEmail" ng-disabled="!myForm.txtemail.$viewValue"
ng-model="EmailConfirm" match match-Email="{{myForm.txtemail.$viewValue}}" match-Cemail="{{EmailConfirm}}" class="form-control" />
You should get into the habit of using the "dot" on the scope; In your situation you should be using:
$scope.model = {
mismatch: false
}
Here's your fixed plunker: https://plnkr.co/edit/XEZjkXaIecGC4oBox5Z0?p=preview

Javascript capture HTML form value for Mixpanel

I have a mailchimp form to sign up for my email list, and mixpanel tracking to detect when the form is submitted.
<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup"><form id="mc-embedded-subscribe-form" class="validate" action="http://fileoptic.us7.list-manage.com/subscribe/post?u=a1a176055d942403ee4c74a11&id=028333dc80" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank"><label for="mce-EMAIL">Subscribe to our mailing list for blog updates:</label>
<input id="mce-EMAIL" class="email" name="EMAIL" required="" type="email" value="" placeholder="email address" />
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input name="b_a1a176055d942403ee4c74a11_028333dc80" type="text" value="" /></div>
<div class="clear"><input id="mc-embedded-subscribe" class="button" name="subscribe" type="submit" value="Subscribe" /></div>
</form></div>
<!--End mc_embed_signup-->
<script type="text/javascript">
mixpanel.track_forms("#mc-embedded-subscribe-form", "Subscribed to Email List");
</script>
I want to extract the submitted email address from the form and use mixpanel.alias to identify users by their email addresses as they navigate around my site.
What code do I use to extract the email address and call mixpanel.alias with it?
I don't know anything about mixpanel, but here are two ways to get the value of an input and store it in a variable for later use.
With jQuery (I prefer this method):
$('#mc-embedded-subscribe-form').on('submit', function(){
var val = $('input.email').val();
console.log(val); // Use this to test the function
});
Or with plain Javascript. First add this to the form tag in your HTML:
onsubmit="getEmail()"
Then the JS function:
function getEmail() {
var elem = document.getElementById('mce-EMAIL');
var val = elem.value;
console.log(val); // For testing
}
Hope that helps :)

When I press enter key, unable to login

I have been trying to log in to a offline HTML/CSS page using the enter key but unable to start with JavaScript which needs I'm sure.
But can log in using the mouse when I click the log in button which i have created ..
How do i use the enter key stroke to log in?
This is the javascript which I have hard coded for credential test which works using the mouse click.. I want it for the enter key.. Thank you.
<!DOCTYPE HTML>
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<div align="center">
<div id="bor">
<h1>
Login Page
</h1>
<div>
<form name="login">
&nbsp<input type="text" placeholder="Enter the Username" name="user"/> <br />
<input type="password" placeholder="Enter the Password" name="pwd"/><br /><br />
<input type="checkbox" name="en" value="en" />Remember Me<br>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</div>
<script language="javascript">
function check(form)
{
if(form.user.value == "user" && form.pwd.value == "pwd")
{
window.open('inbox.html','_self')
}
else
{
alert("Error Password or Username")
}
}
</script>
Use the submit event handler. The click handler on an element will only fire if you click on it. What you are trying to do is submitting a form, but handling the form with javascript instead of on the server. I would recommend binding that dynamically, but as you have all javascript here inline, I'll give an example inline too.
You'll need to attach a submit event handler to the form element. If you do it inline, this will work with onsubmit="..." instead. The return is there to prevent/allow the form to be submitted to the server. If the function returns 'true', the form will be submitted to the server. If the function returns 'false', the form will not be submitted. You'll also need to change the type of your submit button to submit. This will tell the browser to submit the form if that button is clicked. Alternatively, if you press enter in an input field, the browser will see this as submitting the form too.
<form name="login" onsubmit="return check(this)">
&nbsp<input type="text" placeholder="Enter the Username" name="user"/> <br />
<input type="password" placeholder="Enter the Password" name="pwd"/><br/><br/>
<input type="checkbox" name="en" value="en" />Remember Me<br>
<input type="submit" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
The javascript behind it will remain mostly the same. You'll notice that we passed this to the function. This will pass the element itself (in this case the form element) to the function. As said before, you'll need to return false. I've changed form to frm as form is a globally defined variable in some browsers.
function check(frm)
{
if(frm.user.value == "user" && frm.pwd.value == "pwd")
{
window.open('inbox.html','_self')
}
else
{
alert("Error Password or Username")
}
return false;
}
An example jsfiddle: http://jsfiddle.net/AS5t5/

customising behaviour of Jquery validate

I am using Jquery validate to provide feedback to a user and provide them updates on the validity of the details they enter in the form. But I am having trouble customising the behaviour Jquery validate creates.
I have a simple form like this:
<form id="form1">
<label for="input1" />
<input name="input1" />
<input type="submit" />
</form>
When the user enters invalid information I want Jquery validate to output something like this:
<form id="form1">
<label for="input1" />
<input name="input1" class="error"/><span class="errorIcon">Error</span>
<p class="errorText">Error message</p>
<input type="submit" />
</form>
When the user fills out the field with valid information I want Jquery validate to output:
<form id="form1">
<label for="input1" />
<input name="input1" /><span class="successIcon">Success</span>
<input type="submit" />
</form>
I have set up the required rules and custom validation messages so they fire fine but I am having trouble getting the behaviour described above.
I have this currently:
$('#form1').validate({
showErrors: function(errorMap, errorList) {
if (errorList < 1 ) {
$('span.errorIcon').remove();
$('p.errorText').remove();
$('input.error').removeClass('error');
$('select.error').removeClass('error');
return;
}
$.each(errorList, function(index, error) {
if ($(error.element).siblings('.errorText').length === 0 && $(error.element).siblings('.errorIcon').length === 0) {
$(error.element).next('p.errorText').remove();
$(error.element).addClass('error');
$(error.element).after(
$('<p/>')
.addClass('errorText')
.append(error.message)
);
$(error.element).after(
$('<span>There is an issue with this field</span>')
.addClass('errorIcon')
);
}
});
},
//rules and messages defined here
);
So the above doesn't achieve what I want need currently and it also feels like I might be over complicating this issue. I am fairly inexperienced with javascript and Jquery. Any guidance in getting this sorted would be appreciated.
Cheers
EDIT:
Here is a link to a jsfiddle: http://jsfiddle.net/WJ9Vt/4/ with the sample form.
Could also post you css file, or do a jsfiddle on it ? Because you errorIcon is probably not shown because <span> will not display something as long as it has no content or you set display:block; and a special height and width.

Categories

Resources