el mashrafi el mashrafi - 3 months ago 6
HTML Question

Validate jquery form how to not allow spaces in Full Name

$(document).ready(function(){
var form = $("#contact_form");
var FName = $("#fname"); //Creates Variables from forms
var FNameInfo = $("#fnameInfo");
var Tele = $("#tele");
var TeleInfo = $("#teleInfo");
var Address = $("#address");
var AddressInfo = $("#addInfo");
var Email = $("#email");
var EmailInfo = $("#EmailInfo");
var regexp = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9.]+.[a-z]{2,4}$/; //ragex code

FName.blur(validateFName); //blur is a method which attaches a functiom to run when an event occurs
Email.blur(validateEmail);
Tele.blur(validateTele);
Address.blur(validateAddress);

form.submit(function(){
jQuery.validator.addMethod("noSpace", function(value, element) { //Code used for blank space Validation
return value.indexOf(" ") < 0 && value != "";
}, "No space please and don't leave it empty");

$("contact_form").validate({
rules: {
name: {
noSpace: true
}
}
});

if (validateFName() & validateTele() & validateEmail() & validateAddress()) { //If it passes all of these then return true
return true;
} else {
return false;
}
});

function validateFName() { //Creates function for Name Validation+
if (FName.val().length < 5) { //If name is length is less than 5
FName.addClass("error"); //Display error
FNameInfo.text("Please Enter Correct Name"); //Changes span name
FNameInfo.addClass("error"); //Same error
FNameInfo.removeClass("Valid");
return false;
}
else {
FName.removeClass("error"); //remove error class
FNameInfo.addClass("Valid")
FNameInfo.text("Thanks Buddy" ); //When user enters correct code this text will appear
FNameInfo.removeClass("error");
return true;
}
}


<div>
<label for="name">Full Name</label>
<input id="fname" name="fname" type="text" />
<span id="fnameInfo">Whats your full name?</span>
</div>


How do I get the validation to work for Full Name when user enters blank spaces? I have the code above but it doesn't seem to do anything. Would I need to change the function parameters?

Answer

"contact_form" needs an # for id or . for class.

and the name for full name is fname.

so:-

$("#contact_form").validate({
    rules: {
       fname: {
         noSpace: true
       }
    }
});

should work.

FIDDLE

Comments