I am working on a web form that must be validated on submit. I have a field for a first name that must follow two rules when validated, the name must have at least 3 letters and there can be no spaces between any of the characters. I have gotten it to display an error message when the name is too short, but I can't figure out how to not allow whitespace.
How can I validate this so that there are no spaces between any characters using javascript?
Here is my code so far:
<html>
<head>
<title>Project 5</title>
</head>
<body>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
First Name: <input type="text" id="name"> <br>
Age: <input type="text" id="age"> <br>
Street Address: <input type="text" id="address"> <br>
State: <select>
<option value="la">LA</option>
<option value="tx">TX</option>
<option value="ok">OK</option>
<option value="mi">MI</option>
<option value="az">AZ</option>
</select> <br>
Login Password: <input type="password" id="password"> <br>
<input type="submit" value="Submit"> <br>
</form>
<script type="text/javascript">
function validateForm() {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
if(input.length < 3) {
alert("Please enter a name with at least 3 letters");
return false;
}
else if(input.length >= 3) {
}
}
</script>
</body>
</html>
there is an option to remove white space of all the text by just using single line of code from Javascript.
text=text.split(' ').join(''); // this will remove all the white space in your text.
I'd recommend using a regex for form input validation. Check examples below:
shouldFailTooShort = 'ts';
shouldFailSpace = 'has space';
shouldPass = 'no-spaces';
validationRule = /^\S{3,}$/;
validationRule.test(shouldFailTooShort) === false;
validationRule.test(shouldFailSpace) === false;
validationRule.test(shouldPass) === true;
Using regular expressions one can have all validation against a field performed in one regular expression check, like presented above. For usability however I'd recommend having one rule for each validation requirement. Then different validation rules can produce different messages and user does not get confused having to read one and always same message.
Have a peek on my favourite regular expression reference.
Edit:
As requested in comment, herein I present my proposal of deploying the solution. I suggest not using alert function in production, but display the message on the page itself, e.g. in a span element.
HTML:
<form name="myForm" id="myForm" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
JavaScript:
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 3) {
errMsgHolder.innerHTML =
'Please enter a name with at least 3 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
} else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
Check live example in jsfiddle.
for (var i=0, len = string.length; i<len; ++i) {
if (string.charAt(i) === ' ') {
alert('Name cannot have spaces!');
break;
}
}
Related
I'm looking for code that validates the Name and Email input's on <Form onsubmit="return validate();">
I want that username has only A-Z,a-z and must have an underscore_, email should have an #. How can i do it with jQuery?
Form(example):
<html>
<head>
<title>TEST</title>
</head>
<body>
<form action="..." method="POST" onSubmit="return Check()" >
<input type="text" id="name" placeholder="Please enter your Name. (Must have underscore)" required>
<input type="text" id="email" placeholder="E-Mail">
<input type="submit" value="submit">
</form>
</body>
</html>
EDIT I've tried:
<script type="text/javascript">
jQuery(document).ready(function($){
$('[name="submit"]').click(function(e){
var name = document.getElementById("name").value;
if(re = /[a-zA-Z]*_[a-zA-Z]*/;) {
$(".name").addClass("error");
return false;
} else {
$(".name").removeClass("error");
$(".name").addClass("success");
return true;
}
});
});
Thanks!
For a valid email address:
Validate email address in JavaScript?
For your username is the same but your regex should be something like this:
re = /^[a-zA-Z]*_[a-zA-Z]*$/; //this always needs an underscore to be valid.
Just in case, this is the regex to accept anything az AZ and _ and nothing, it depends on your requirements:
re = /^[a-zA-Z_]*$/;
re = /^[a-zA-Z_]{3,}$/; //3 or more chars
To test your regex:
re = /^[a-zA-Z_]*$/;
return re.test('any_string_to_test'); //it returns true if your string is valid
Using regex with jquery:
Pass a string to RegExp or create a regex using the // syntax call
regex.test(string) not string.test(regex)
In your code:
$(".name").on('keyup', function(e)
{
var name = $(this).val();
if(new RegExp(/^[a-zA-Z_]+$/i).test(name)) // or with quotes -> new RegExp("^[a-zA-Z_]+$", 'i')
$(this).addClass("error");
else
$(this).switchClass("error", "success", 1000, "easeInOutQuad");
e.preventDefault();
e.stopPropagation(); // to avoid sending form when syntax is wrong
});
And for email input, the following regex can do the job :
/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
Or..
To put a little bit of modernity, you can use html5 email field type
<input type="email" id="email">
Now using the advanced feature of HTML5 it's eaiser, you can simply do the validation as follow:
<form action="" method="">
<!-- Name containing only letters or _ -->
Name: <input type="text" name="name" pattern="[a-zA-Z][[A-Za-z_]+" />
<!-- using type email, will validate the email format for you-->
Email: <input type="email" id="email" />
<input type="submit" value="Submit">
</form>
Check HERE for more form validation features of HTML5.
#Polak i tried so, if i understand what you mean :x Sorry i'm new with javascript.
<script type="text/javascript">
jQuery(document).ready(function($){
$('[name="submit"]').click(function(e){
var name = document.getElementById("display_name").value;
re = /[a-zA-Z]*_[a-zA-Z]*/;
if (re.test(name) {
//Things to do when the entry is valid.
$(".NameCheck").removeClass("name_error");
$(".NameCheck").addClass("name_success");
return true;
} else {
//Things to do when the user name is not valid.
$(".NameCheck").addClass("name_error");
return false;
});
});
});
This function is for validation. It prints am error if it's empty and shows either red or green along with an OK msg beside the text box.
JavaScript
function validatebox()
{
var fn = document.geElementById("fn").value;
if (fn==null || fn=="")
{
document.geElementById("error_fn").innerHTML="please fill your first name";
document.geElementById("error_fn").style.color="red";
}
else
{
document.geElementById("error_fn").innerHTML="OK";
document.geElementById("error_fn").style.color="green";
}
I am trying to display the error message beside the text box but its not working.
HTML
<form name="signup" action="singup_i" method="post">
First name:
<input type="text" id="fn" onblur="validatebox()" name="fn" size="15"/>
<label id="error_fn"></label>
<input type="submit" value="submit"> <input type="reset" value="reset">
</from>
Three problems:
It's getElementById (note the t), not geElementById.
You're missing the ending } on your function.
Your closing tag for the form is </from>, not </form>
Your browser was probably telling you about at least the first two: In all modern browsers, there's a full set of development/debugging tools. For IE and Chrome (at least), just press F12. For others, look in the menus.
Fix those and it works: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Example</title>
</head>
<body>
<form name="signup" action="singup_i" method="post">
First name:<input type="text" id="fn" onblur="validatebox()" name="fn" size="15"/>
<label id="error_fn"></label>
<input type="submit" value="submit"> <input type="reset" value="reset">
</from>
<script>
function validatebox() {
var fn = document.getElementById("fn").value;
if (fn == null || fn == "") {
document.getElementById("error_fn").innerHTML = "please fill your first name";
document.getElementById("error_fn").style.color = "red";
}
else {
document.getElementById("error_fn").innerHTML = "OK";
document.getElementById("error_fn").style.color = "green";
}
}
</script>
</body>
</html>
Note that I've reformatted the function code a bit, so it's easier to see the blocks (and therefore see the ending }).
But can I suggest not looking up the error_fn repeatedly, and not using a label element for something other than labelling a field: Live Copy | Live Source
<form name="signup" action="singup_i" method="post">
First name:<input type="text" id="fn" onblur="validatebox()" name="fn" size="15"/>
<span id="error_fn"></span>
<input type="submit" value="submit"> <input type="reset" value="reset">
</form>
<script>
function validatebox() {
var fn = document.getElementById("fn").value;
var err = document.getElementById("error_fn");
if (fn == null || fn == "") {
err.innerHTML = "please fill your first name";
err.style.color = "red";
}
else {
err.innerHTML = "OK";
err.style.color = "green";
}
}
</script>
Finally, fn will never be null, because the value property of a text field will never be null; it's always a string. The string may be blank. In this case, the easiest test would just be if (!fn) { /* missing */ } else { /* present */}, which will test fn to see if it's null, undefined, 0, "", false, or NaN (of which, it can only be "", because again value is always a string). Of course, " " (a space) would get past that.
Many errors:
getElementbyId not geElementbyId
form not from
End your input with /
Basically, I tried to add a form to my website and when the Confirm/Submit button is clicked, the program with check if the Name & e-mail form have to the correct information, otherwise a warning will be displayed.
<script language="javascript" type="text/javascript">
function validateForm()
{
var x=document.forms["form1"]["name"].value;
if (x==null || x=="")
{
alert("Please enter your name");
return false;
}
}
function validateForm()
{
var x=document.forms["form1"]["e-mail"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter your e-mail address");
return false;
}
}
</script>
</head>
<body>
<h2>Form</h2>
<p>Note: Please fill in the following fields below, thank you.</p>
<form id="form1" name="form1" method="post" action="post">
<p>
<label for="name">Name:</label>
<br />
<input type="text" name="name" id="name" />
</p>
<p>
<label for="e-mail">E-mail:</label>
<br />
<input type="text" name="e-mail" id="e-mail" />
</p>
<p>
<label for="msg">Message:</label>
</p>
<p>
<textarea name="msg" id="msg" cols="45" rows="5"></textarea>
</p>
<p>
<input type="button" name="Confirm" id="Confirm" value="Submit" />
</p>
<!-- end .content -->
</form>
</div>
<div class="sidebar2">
<h4> </h4>
<p> </p>
<p><!-- end .sidebar2 --></p>
</div>
<div class="footer"> <img src="pics/copyright.gif" width="960" height="100" alt="footer" /></div>
<!-- end .container --></div>
</body>
</html>
In your code:
> <script language="javascript" type="text/javascript">
The language attribute has been deprecated for about 15 years, the type attribute is no longer required, so:
<script>
> function validateForm () {
> var x=document.forms["form1"]["name"].value;
It is handy to pass a reference to the form from the listener so the function can be more generic. Also, named form controls are added as named properties of the form. If you have a control with a name that is the same as a form property, it will overwrite the form property so you can't access it as a property. Much better to avoid standard property names for element names and IDs, so:
function validateForm(form) {
var x = form.userName.value
then:
> if (x == null || x == "") {
The value of a form control is a string, so x == null will never be true. It's sufficient (and more suitable) to just test:
if (x == "") {
[...]
> function validateForm() {
If you declare multiple functions with the same name, each will overwrite the previous one so you are left with just the last one. You should have a single validation function that does the checks, though each check might be a separate function.
> var x=document.forms["form1"]["e-mail"].value;
> var atpos=x.indexOf("#");
> var dotpos=x.lastIndexOf(".");
> if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
> {
> alert("Please enter your e-mail address");
> return false;
> }
> }
You can use a regular expression to check the format of the e–mail address.
> <form id="form1" name="form1" method="post" action="post">
There generally isn't a need for ID and name attributes on a form, typically just an ID is used. For other form controls, a name is required for them to be successful, there is rarely a need for them to have an ID.
The validation function can be called from the form's submit event, so:
<form id="form1" onsubmit="validateForm(this);" ...>
[...]
> <input type="text" name="name" id="name" />
Don't use XML markup in an HTML document. And don't use element names that are the same as form attribute names as they will make the related form property inaccessible.
</p>
<p>
<label for="e-mail">E-mail:</label>
<br />
Message:
If that is a submit button, then make it type submit. It doesn't need a name or ID if it's value isn't to be submitted:
<input type="submit" value="Submit">
So your form and code can be:
function validateForm(form) {
var reUserName = /\w+/; // User name has some letters
var reEmail = /.+#..+\..+/; // email has some characters, #, then a dot near the end
var passed;
if (!reUserName.test(form.userName.value)) {
passed = false;
// show message for user name
}
if (!reEmail.test(form.eMail.value)) {
passed = false;
// show message for email
}
return passed;
}
Note that the e–mail validation is just what you have, which is not particularly thorough.
Then the form:
<form onsubmit="return validateForm(this);">
Name: <input name="userName"><br>
E-mail: <input name="eMail"><br>
<input type="submit">
</form>
just indent your code and it should be fine, I would love to help, but without seeing the code there's not much i can do. Maybe a link to the page on your site?
I am a beginner and I have written a code for validating the form as:
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
alert("First name must be filled out");
return false;
}}
<!-- html part-->
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><br>
The problem with this code is pressing submit button triggers the validateForm function. How to call the function when the object losses focus?
This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:
<script>
function validate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
y.innerHTML = "Error";
}
}
</script>
The HTML form is:
<form name="myForm">
First name: <input type="text" name="fname" onBlur = "validate()">
<div id = "errorResponse"></div>
<input type="submit" value="Submit">
</form>
The div can be designed in CSS to red color to get user attention and many more tricks can be played.
replace your input element's code by following
<input type="text" onblur="return validateForm();" name="fname">
i guess thats what you are looking for
<html>
<head>
<script type="text/javascript">
function validateForm(oForm){
var els = oForm.elements;
for(var i = 0; i < els.length; i++){
if('string' === typeof(els[i].getAttribute('data-message'))){
return valEl(els[i]);
}
}
}
function valEl(el){
var method = el.getAttribute('data-valMethod');
if('req' === method && (el.value === null || el.value === '')){
alert(el.getAttribute('data-message'));
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="#" onsubmit="return validateForm(this)" method="post">
First name:
<input data-message="First name must be filled out" data-valMethod="req" onchange="return valEl(this)"; name="fname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element.
Since HTML5 the Data-* attributes are very handy for these things :-)
This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.
From here you can expand the valEl-function to accommodate other types of validation.
Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.
Happy coding.
/G
PS http://jsfiddle.net/ePPnn/11/ for sample code
For some reason, this code always redirects to education.php regardless of whether or not the fields are blank. I want to verify the fields have values in them, but for some reason they keep redirecting but not writing anything in the database. Any help would be greatly appreciated.
<body>
<form action="education.php" method="post" onsubmit="return validate_fields()">
<div style="text-align: right">
<ul>
First Name: <input id="first_name" name="first_name" size=25/> <br>
Last Name: <input id="last_name" name="last_name" size=25/> <br>
Email: <input id="emailaddress" name="emailaddress" size=25/> <br>
Password: <input id="user_password" name="user_password" type="password" size=25/> <br>
<center><input type="submit" name="submit" id="submit" value="Register Now"/></center>
</ul>
</div>
</form>
<script type="text/javascript">
function validate_fields()
{
var first_name = document.getElementByID("first_name").value;
var last_name = document.getElementById("last_name").value;
alert(""+first_name+" "+last_name);
if (first_name.length < 1 || last_name.length < 1)
{
alert("Please fill in your name.");
return false;
}
var email = document.getElementById("emailaddress").value;
if (email.length < 1)
{
alert("Please fill in your email address.");
return false;
}
var password = document.getElementById("password").value;
if (email.length < 1)
{
alert("Please put in a password.");
return false;
}
alert(first_name+" "+last_name+" "+email);
return false; //was true, changed to see if still redirects.
}
</script>
</body>
You've got a typo on the first line of your function so it isn't returning false (or true), it is just not running at all. This explains both why you don't get any of the alerts and why the form submit goes ahead.
var first_name = document.getElementByID("first_name").value;
// you need a lowercase "d" here ------^
It should be .getElementById(), not .getElementByID().
This is the sort of thing you can easily find for yourself with the appropriate developer tools for your browser. Chrome has this built in (just press ctrl-shift-J to bring up dev tools), or you can add Firebug for FireFox, and IE has had a dev toolbar option for several versions now.
You have a typo here:
var first_name = document.getElementById("first_name").value;
You wrote ByID it sould be ById!