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
Related
I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
This is my code for my login page:
http://pastebin.com/RGVrW0Hi
It's the field right under the body tag.
All the way down there is a scipt tag with my function. I'm trying to check if the user has typed something inside the "Navn" field, if not it should return false.
I have tried it in a smaller page that look like this:
http://pastebin.com/d1vzyDvd
Can anyone point me in the right direction?
If you want to get any field by name use
var value = document.getElementsByName("navn")[0].value;
// By Id
var value = document.getElementsById("navn").value;
Use document.getElementsByName("navn").value[0] instead of document.famular.navn.value to get the value of an input field by its name.
function validerform125() {
if (document.getElementsByName("navn")[0].value == "") {
alert("NEEEJ!!!");
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form name="famular" action="vanillahost.html" method="post" onsubmit="return validerform125()">
Navn
<input name="navn" type="text">
<br/>Email
<input name="email" type="email">
<br/>
<div>
<input type="submit" name="send" value="send">
</div>
</form>
You add [0] to document.getElementsByName("navn") because getElementsByName returns a NodeList object which represents a collection of elements with the specified name (In your case: "Navn"). By adding [0] you are basically returning the first element found.
better if you can include jquery in your html, will give you a nicer interface to interact with html elements.
In java-script you can try the following code
<body>
<div>
<form name="famular" action="vanillahost.html" method="post" onsubmit="return validerform125()">
Navn <input name="navn" type="text"><br/>
Email <input name="email" type="email"><br/>
<div>
<input type="submit" name="send" value="send">
</div>
</form>
</div>
</body>
<script>
function validerform125() {
var x = document.forms["famular"]["navn"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
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 trying to run a javascript code but it is not running. I don't know why?
Here is the code sample:
Javascript:
<Script Language="text/Javascript">
function validateForm()
{
var x=document.forms["form1"]["Injection"].value;
var y=document.forms["form1"]["limit"].value;
if (x==null || x=="")
{
alert("Injection must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Limit must be filled out");
return false;
}
return true;
}
</Script>
HTML:
<form name="form1" method="post" action="/OT_Stock/addnewinjection.jsp" onsubmit="return validateForm()">
<input type="text" name="Injection" maxlength="100" size="20" value="" style="textfield">
<input type="text" name="limit" maxlength="100" size="20" value="" style="textfield" >
<input type="submit" value="Add Name" class="buttonmain">
Please tell me where I am going wrong?
Remove the onclick from the button
Add onsubmit="return validateForm()" to the form element.
The crucial bit is the return keyword. Without it the form will always submit. With it, when the validateForm method returns false (invalid form) the form will not submit.
Edit: OP has updated his question with the above suggestions.
forma name is " form1", instead of it should be "form1".Don't use language in the script tag instead use type='text/javascript'.
I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.
HTML:
<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">
<div id="errors"></div>
<label for="author">Name:</label><br/><br/>
<input type="text" name="author" id="message" /><br/><br/>
<label for="author">Message:</label><br/><br/>
<textarea name="message" id="message"></textarea><br/><br/>
<input type="submit" class="button" value="Send Message"/>
</form>
Javascript:
<script type="text/javascript">
function error(message){
return "<p class=\"error\">"+message+"</p>";
}
function validate(){
var form = document.getElementById("contactForm");
var author = document.getElementById("author");
var message = document.getElementById("messsage");
var errors = document.getElementById("errors");
alert(author.value);
if(message.value == '' || author.value == ''){
errors.innerHTML = error("Please fill in all fields.");
return false;
} else {
return true;
}
}
</script>
id=author on your first input element.
Also check out jQuery it will save you time in the long run
You have two elements with the id message and none with author.
The Markup Validator would have picked this up for you.
var message = document.getElementById("messsage");
message has an extra "s".
<input type="text" name="author" id="message" />
You need to change "message" to "author"
This is wrong:
<input type="text" name="author" id="message" />
Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.
Also both your label tags have for="author"; the second one is wrong.
I guess your problem here is too much copy+paste. ;)