Reputation: 1801
Good day. On the beginning I would like to apologize for the big mess in the last part of code. I have a problem with validating my pre-filled form. So what I have done so far is a form with pre-filled values. When user clicks on the field it removes pre-filled value. I was trying to validate this form against empty fields, but as long as they are pre-filled it doesn't show there is a missing string.
Let me present the HTML:
<form action="" method="post" id="form1" class="form" action="scripts/form-quote.php">
<input class="swap validate" id="name" name="name" type="text" value="Name" /> <p id="iname" class="validation-error"></p>
<input class="swap emailvalid" id="email" name="email" type="text" value="E-mail" /> <p id="iemail" class="validation-error"></p>
<textarea class="swap validate" id="add-req" name="add-req" cols="43" rows="8" >Please explain your requirements</textarea> <p id="iadd-req" class="validation-error"></p>
<input class="swap" id="ad" name="ad" type="text" value="Where did you hear about us?" />
<input class="submit" name="Submit" type="submit" value="Send">
</form>
and jQuery - this part is working OK:
$.fn.swapText = function(){
return this.each(function(){
var tmpDefVal = $(this).val();
$(this).css('color', '#999');
$(this).focus(function(){
if($(this).val() == tmpDefVal){
$(this)
.css('color', '#000')
.val('');
}
});
$(this).blur(function(){
if($(this).val() == ''){
$(this)
.css('color', '#999')
.val(tmpDefVal);
}
});
});
};
$(document).ready(function(){
$('.swap').swapText();
});
jQuery - this is a complete mess. I was trying to recreate the existing one which I've done a long time ago with some help, but it was validating against the empty fields. Now I want to validate it against the prefilled fields:
function isNotEmpty(string){
if(string.length < 1){
return false;
}else{
return true;
}
}
function checkOnChange(){
var infoField = document.getElementById('i'+this.id);
if(this.type == 'checkbox'){
if(this.checked){
infoField.innerHTML = '';
}else{
infoField.innerHTML = 'Required field';
}
}else{
if(isNotEmpty(this.value)){
this.className = 'ok';
infoField.innerHTML = '';
//this.style.backgroundColor = '';
}else{
//this.style.backgroundColor = 'red';
this.className = 'err';
infoField.innerHTML = 'Required field';
}
}
}
$(document).ready(function(){
$('.swap').swapText();
$('#email').swapText();
$('#email').keyup(function(){
var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(regexp.test($(this).val())){
$(this).removeClass('err');
$(this).addClass('ok');
}else{
$(this).removeClass('ok');
$(this).addClass('err');
}
});
});
window.onload = function(){
var inputName = document.getElementById('name');
var inputMsg = document.getElementById('add-req');
document.forms[0].onsubmit = function(){
var formValid = true;
if(isNaN(this.nrklienta.value)){
}else{
}
if(!isNotEmpty(this.pers.value)){
var infoField = document.getElementById('i'+this.pers.id);
this.pers.className = 'err';
infoField.innerHTML = 'Required field';
formValid = false;
}else{
}
//return false;
if(formValid){
return true;
}else{
return false;
}
}
}
//* Email validation
$(document).ready(function(){
$('#email').swapText();
$('#email').keyup(function(){
var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(regexp.test($(this).val())){
$(this).removeClass('err');
$(this).addClass('ok');
}else{
$(this).removeClass('ok');
$(this).addClass('err');
}
});
});
Sorry for the big mess in the last part of code, but this is just to show what I'm trying to achieve. So if the user won't fill the #name, #email (validation code for email should be working, no idea why it doesn't) and #add-req (or better if it can be done by class .validate) then after clicking Send button it will not send a form but display a message in p (.validation-error) "Required field" + change class of the actual field.
The jsFiddle here
Upvotes: 0
Views: 2112
Reputation: 9706
Instead of a prefilled value, you should be using the <label>
element for each <input>
and the placeholder
attribute.
For example, just taking one of your inputs, you could use:
<label for="email">E-mail:</label>
<input class="swap emailvalid" id="email" name="email" type="text" placeholder="E-mail" />
You can hide the label with CSS if you don't want it displayed, but it should still be present for non-sighted users.
You will find that using a placeholder will spare you from jumping through all sorts of hoops in your code to achieve the desired result. Allow me to demonstrate. (If jsfiddle.net is still down, use http://jsbin.com/akesep/2/edit.)
Use the following HTML:
<form method="post" id="form1" action="scripts/form-quote.php">
<ul>
<li>
<label for="name">Name</label>
<input class="required" id="name" name="name" type="text" placeholder="Name" />
</li>
<li>
<label for="email">E-mail:</label>
<input class="required" id="email" name="email" type="text" placeholder="E-mail" />
</li>
<li>
<label for="add-req">Message</label>
<textarea class="required" id="add-req" name="add-req" cols="43" rows="8" placeholder="Please enter your message"></textarea>
</li>
<li>
<label for="ad">Referrer</label>
<input id="ad" name="ad" type="text" placeholder="Where did you hear about us?" />
</li>
</ul>
<button type="submit">Send</button>
</form>
Nice and clean markup. No prefilled values to complicate the javascript. Placeholders and labels used properly.
Then the following jQuery script will validate for completion of required fields and valid email:
var addErrorMessage = function (field) {
var err = $(document.createElement('p')).addClass('validation-error').text('Required field');
field.addClass('err').after(err);
},
clearError = function () {
var t = $(this);
if (t.hasClass('err')) {
t.removeClass('err');
t.next('p').empty().remove();
}
},
isEmpty = function (str) {
return str.trim().length < 1;
},
isValidEmail = function (str) {
var regexp = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regexp.test(str);
},
validateForm = function () {
var requiredFields = $(this).find('.required'),
email = $('#email'),
fieldsValidate = true;
// check that required fields are not empty
requiredFields.each(function () {
var t = $(this);
if (isEmpty(t.val())) {
fieldsValidate = false;
if (!t.hasClass('err')) {
addErrorMessage(t);
}
}
});
// check that email is valid
if (!isValidEmail(email.val().trim())) {
fieldsValidate = false;
if (!email.hasClass('err')) {
addErrorMessage(email);
}
}
return fieldsValidate;
};
$('input, textarea').keyup(clearError);
$('#form1').submit(validateForm);
You can easily add other types of validation as well following the same principles, but this should give you a good start.
Upvotes: 2