How can give CSS for Javascript Error Message - javascript

Here is the Demo
I am working in Javascript Validation. I want to give Separate colour for the text
" Please enter Valid Email ID "
When User Enter a wrong email id and press, there is one Error message will come. I want give red colour for this Error message. Only for this Error message i need red colour
HTML
<label id="message">We don't Spam. Promise</label> <br />
<input autocomplete="on" type="text" name="booking_email" onkeyup="validate()" id="SignupText" class="InputSignup" placeholder="Enter Your Email" />
<input type="submit" value="submit" class="subButton" onclick="submitEmail();"/>
JAVASCRIPT
function validate()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email == '' ){
document.getElementById("message").innerHTML="We don't Spam. Promise";
}else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
document.getElementById("message").innerHTML="Your email is valid"
if(event.which == 13){
submitEmail();
}
} else {
document.getElementById("message").innerHTML="Type your email id";
if(event.which == 13){
submitEmail();
}
}
}
function submitEmail()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email=="")
{
document.getElementById("message").innerHTML="Please enter Your Email ID"
}
else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
alert('success');
}
else {document.getElementById("message").innerHTML="Please enter Valid Email ID";}
}

just change
document.getElementById("message").innerHTML="Please enter Your Email ID"
to
document.getElementById("message").innerHTML = "<span style='color:red'>Please enter Your Email ID</span>";
wrapping the text with a span that has the color set to red ?

I created a JSFiddle
I wrapped a <span class='red'></span> around the text and then created a class .red in the css.
Javascript:
document.getElementById("message").innerHTML = "<span class='red'>Please enter Your Email ID</span>";
CSS
.red{
color:red;
}

Whenever you print an error message you could wrap it in a div with a class or error-message
document.getElementById("message").innerHTML="<div class='error-message'>Please enter Valid Email ID</div>";
Then in your CSS file you can do
.error-message
{
color: red;
}

I would recommend:
css:
.error {
color: red;
}
and:
document.getElementById("message").innerHTML = "<span class='error'>Please enter Your Email ID</span>";
Other option would be to keep separate div for your errors and change its visibility and or text accordingly.
However, ultimate solution would be just to use correct input type.
<input type="email" name="email">
it works best as cross-device and it has error handling build in using regexp, so you can get away using those nasty javascript codes :) read more:
http://html5doctor.com/html5-forms-input-types/

friend try this code.. i have used jquery css method which makes solution very easier.you don't need to create class and div for message.You just need to follow below code. I have used jquery css method and I have used it only in success message,but you can use it for all.Just follow the syntax.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function validate()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email == '' ){
document.getElementById("message").innerHTML="We don't Spam. Promise";
}else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
document.getElementById("message").innerHTML="Your email is valid"
$('#message').css("color","red");
$('#message').css("font-weight","bold");
if(event.which == 13){
submitEmail();
}
} else {
document.getElementById("message").innerHTML="Type your email id";
if(event.which == 13){
submitEmail();
}
}
}
function submitEmail()
{
var booking_email = $('input[name=booking_email]').val();
if(booking_email=="")
{
document.getElementById("message").innerHTML="Please enter Your Email ID"
}
else if( /(.+)#(.+){1,}\.(.+){2,}/.test(booking_email) )
{
alert('success');
}
else {document.getElementById("message").innerHTML="Please enter Valid Email ID";}
}
</script>
</head>
<body>
<label id="message">We don't Spam. Promise</label> <br />
<input autocomplete="on" type="text" name="booking_email" onkeyup="validate()" id="SignupText" class="InputSignup" placeholder="Enter Your Email" />
<input type="submit" value="submit" class="subButton" onclick="submitEmail();"/>
</body>
</html>
here is demo
http://jsfiddle.net/JHHTw/3/

Related

How can I have form validation using JavaScript?

I am trying to create a form that checks for JavaScript validation before it goes into my database basically if a user does not type in anything then a alert will come up, however when viewing it in the browser, when I don't place any text inside any of the text boxes and hit submit, no alert comes up, no nothing i'd appreciate it if you could help me out please
HTML
<body>
<form action="update.php?eventID=<?=$contact['eventID']?>" name="myForm" onsubmit="return validate()" method="post">
<label for="eventTitle">Event Title</label>
<input type="text" name="eventTitle" value="?=$contact['eventTitle']?>" id="eventTitle">
<label for="eventDescription">Event Description</label>
<input type="text" name="eventDescription" value="<?=$contact['eventDescription']?>" id="eventDescription">
<label for="eventStartDate">Event Start Date</label>
<input type="text" name="eventStartDate" value="<?=$contact['eventStartDate']?>" id="eventStartDate">
<label for="eventEndDate">Event End Date</label>
<input type="text" name="eventEndDate" value="<?=$contact['eventEndDate']?>" id="eventEndDate">
<label for="eventPrice">Event Price</label>
<input type="text" name="eventPrice" value="<?=$contact['eventPrice']?>" id="eventPrice">
<input type="submit" value="Update">
</form>
<script src="update.js"></script>
</body>
JavaScript
function validate() {
if( document.myForm.eventTitle.value == "" ) {
alert( "Please enter a Event Title" );
document.myForm.eventTitle.focus() ;
return false;
}
if( document.myForm.eventDescription.value == "" ) {
alert( "Please enter a event Description!" );
document.myForm.eventDescription.focus() ;
return false;
}
if( document.myForm.eventStartDate.value == "" ) {
alert( "Please enter a event Start Date!" );
document.myForm.eventStartDate.focus() ;
return false;
}
if( document.myForm.eventEndDate.value == "" ) {
alert( "Please enter a event End Date!" );
document.myForm.eventEndDate.focus() ;
return false;
}
if( document.myForm.eventPrice.value == "" ) {
alert( "Please enter a event End Date!" );
document.myForm.eventPrice.focus() ;
return false;
}
return( true );
}
The only error I found in your code is a missing minor sign before question mark in the line where you define eventTitle
Fix the typo, try clearing browser cache, and try pressing F12 to access debug information to better understand what's going wrong.
You have given value for each input e.g. value="?=$contact['eventTitle']?>"
If you remove that you will get an alert.

JavaScript username and password verification

I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd

Jquery/Form - check input field is at least 5 characters long - and also doesn't match certain words

I have a very simple form. Full Name/Email. What I want to do is check with jquery to make sure that they entered AT LEAST 5 characters in the name field. And if they did not, then I don't want the form to be submitted, instead I want to print some HTML below the form showing a warning/error message. How can I accomplish this?
Also Can I add words manually to the script to make sure they were not entered in the name field? And if they were to make sure it prints errors again... For example, if they entered the word "bobby" or "stephanie" I don't want the form to be submitted if those EXACT words are entered. It is only like 5 or 6 words I want blocked, so I can enter them manually no problem in the script without bloating anything.
Thank you so much in advance.
Here is my HTML
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1">
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email">
</div>
And this is the added HTML I want printed if the jquery check is false
<div id="error">
<span class="error_message">Please enter your full name</span>
</div>
Let's assume your form has an id of myForm.
var words = ["bobby", "stephanie"];
jQuery('#myForm').on('submit', function(evt) {
var form = $(this);
var full_name = form.find('#full_name');
var name_length = full_name.val().length;
if( name_length < 5 ) {
jQuery('#error').show();
evt.preventDefault();
}
if( jQuery.inArray(full_name.val(), words) ) {
evt.preventDefault();
}
});
Here is my answer: there are two if statements that we can construct:
Test if length of input exceeds 5 characters, and
Test if the input matches a list of banned words (stored in an array for convenience and verbosity)
It is a little complicated with the second conditional statement, since we want an exact match (therefore, using 'bobby' will raise a flag, but not 'bobby123'. This involves the use of word boundaries, \b.
You can view the code in action in this fiddle: http://jsfiddle.net/teddyrised/kmMcC/
$('form').submit(function(e) {
var errorFlag = 0,
bannedWords = [
'bobby',
'stephanie'
],
bannedObj = new RegExp('\\b'+bannedWords.join('|')+'\\b', 'i');
if($('#full_name').val().length <= 5) {
errorFlag = 1;
}
if(bannedObj.test($('#full_name').val())) {
errorFlag = 1;
}
// Act on error flag, prevent form submission when one or more error flags are raised
if(errorFlag) e.preventDefault();
});
Assuming you put this all in a form element, and add an input type='submit' element to it, I would suggest setting the form's onsubmit attribute to "return Validate();", and add the below validation function.
First you'll want to hide the message on ready using: $('error').hide();
function Validate(){
var minLength = 5;
var blockedNames = ["bobby","stephanie"];
var fName = $('#full_name').val();
if(fName.length < minLength){
$('#error').show();
$('#full_name').focus();
return false;
}
for(var i = 0;i < blockedNames.length;i++){
if(fName == blockedNames[i]){
$('#error').show();
$('#full_name').focus();
return false;
}
}
return true;
}
JSFIDDLE DEMO: http://jsfiddle.net/softvar/hv6yB/2/
UPDATE:
HTML
<form onsubmit="return check()">
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1" />
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email" />
</div>
<input type="submit" value="Submit"/>
</form>
<div id="error" >
<span class="error_message">Please enter your full name</span>
</div>
CSS
#error {
color:red;
display: none;
border: 1px solid #D9534F;
background: #FDF7F7;
width: 80%;
height: 25px;
padding: 5px;
}
JS
function check() {
var bannedWords = ['bobby','stephen'];
var name= $('#full_name').val();
if(name){
if(name.length>5){
for(var i=0;i<bannedWords.length;i++) {
if(bannedWords[i] ==name){
$('#error').text('Its a banned word');
$('#error').css('display','inline-block');
return false;
}
}
alert('form is going to be submitted');
return true;
}
else{
$('#error').text('Name is shorter');
$('#error').css('display','inline-block');
return false;
}
}
$('#error').text('Name cant be blank');
$('#error').css('display','inline-block');
return false;
}

Validation is not working in second time button click

I am adding username and email to the userlist and validating email when adding. Validation is working when the page loads for the first time, If I tried to enter invalid email for second time and click the add button it is not working..
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
<script type="text/javascript">
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email');
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
</script>
<style>
.errorclass{
border:1px red solid;
}
</style>
Each time there is a validation error you add 'errorclass' to the email class. So the second time is "errorclasserrorclass" that is not defined in the css.
Use:
email.setAttribute('class','errorclass')

Validate optional form fields with default values

Here's my javascript:
$("#cname, #cemail, #curl, #ccomment").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("");
}
}).blur(function() {
if( !this.value.length ) {
$(this).val(this.defaultValue);
}
});
$.validator.addMethod("noName", function(value, element) {
return value != element.defaultValue;
}, "Please enter your name.");
$.validator.addMethod("noComment", function(value, element) {
return value != element.defaultValue;
}, "Please enter your comment.");
$("#commentForm").validate();
The actual form:
<form id="commentForm" action="">
<p>
<input id="cname" name="name" size="25" class="required noName" value="Name">
</p>
<p>
<input id="cemail" name="email" size="25" class="email" value="Email">
</p>
<p>
<input id="curl" name="url" size="25" class="url" value="URL">
</p>
<p>
<textarea id="ccomment" name="comment" rows="5" cols="35" class="required noComment">Comment</textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</form>
And here's a test: http://dl.dropbox.com/u/4017788/Labs/form-validation.html
If you click the submit button, you get error messages on Email and URL fields while they are optional. How can I prevent it?
Simple approach: add an igonre class to Email and URL fields and removeClass / addClass on focus / blur. Test:
http://dl.dropbox.com/u/4017788/Labs/form_validation.html
see validate options for more information.
Alternatively you can completely get rid of the class attribute and then:
on focus >> this.className = 'url'
on blur >> this.className = ''
without changing the validate call.
You can't use the classes 'url' and 'email' for those two form fields, because the plugin is going to try and validate them because they are 'reserved' classes in the plugin . I would suggest trying doing something like this for both the email and url fields.
I haven't tried this, but it suggests that you can custom, but not required field.
You could use the HTML5 placeholder element all the same, but test for placeholder support and then polyfill for it if not available, for example
//test
function placeholderIsSupported() {
var test = document.createElement('input');
return ('placeholder' in test);
}
//polyfill
if(!(placeholderIsSupported())) {
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function () {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
However, strictly speaking what you're doing is providing labels rather than example values for the inputs, so it would probably be more correct/standards-y to use elements <label> and position them behind the inputs, and then hide them when the inputs are focused/have non-empty values, eg:
HTML:
<p class="row">
<label for="name">Name</label>
<input id="cname" name="name" size="25" class="required noName" value="">
</p>
CSS:
.row {
position: relative;
}
input,
label {
display: block
}
label {
position: absolute;
/*tweak these until label correctly positioned behind input*/
top: 0;
left: 0;
}
input {
background-color: transparent;
}
input:focus,
input.has-value {
background-color: #fff; //hide the label behind the bg color when focused or non-empty
}
jQuery:
//toggle a class depending on whether an input has content or not
input.on('blur', function(){
var $this = $(this);
if ($this.val === "") {
$this.removeClass('has-value');
}
else {
$this.addClass('has-value');
}
});
This second option is more semantic and more accessible too, given that screen reader support for placeholder is patchy

Categories

Resources