Created a form. I just want to make form validation. Used javascript to do the job here. Inside jS code created a function named check. In that function if some user leaves the input field blank then the function returns false and in that way I think, can restrict user, but not happening. My question is addressing both getElement..() method and as well as form validation.
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname').value;
//checks the inpur field and it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>
The problem is that getElementsByClassName returns an array, so you should use either document.getElementsByClassName('fname')[0].value or document.querySelector('.fname').value (querySelector returns only first found entity)
Here is my complete code after execution.
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname')[0].value;
//var fname = document.querySelector('.fname').value;
//checks the input field and if it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>
Related
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>
i have two separate JS methods that validates the email and password.
My problem is that when i return both methods on the submit of the html form, the form passes even if the validation fails, but when i return only one method , it works absolutely fine!
<form method="POST" action="http://127.0.0.1:3000/" enctype="multipart/form-data" name="form" onsubmit="return validateEmail(), checkPassword();">
<div class="reservation">
<div class="section_room">
<h5>Enterprise ID: </h5>
<input name="enterpriseID" type="text" name="uName" id="uName" placeholder="me#me.com" class="textbox" required>
</div>
<div class="section_room">
<h5>Password: </h5>
<input name="password" type="password" name="PassWd" id="passWd" placeholder="Password1!" class="textbox" required>
</div>
<input type="submit" value="Login" style="width: 280px;">
<div class="clear"></div>
</ul>
</div>
</form>
AND MY JS IS:
</script>
function validateEmail(){
var email = document.getElementById('uName');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
email.focus;
return false;
}
else
return true;
}
function checkPassword()
{
var pass = document.getElementById('passWd');
var re = /^(?=(.*\d){1})(?=.*[a-zA-Z])(?=.*[!##$%^&*])[0-9a-zA-Z!##$%]{8,}/;
if (!re.test(pass.value))
{
alert('Your Password does not meet the minimun requirements');
email.focus;
return false;
}
else
return true;
}
</script>
Where have i wen wrong, or is this even possible?
Change your onsubmit to check against both values using a logical AND (&&):
When used with Boolean values, && returns true if both operands are true; otherwise, returns false.
onsubmit="return validateEmail() && checkPassword();"
Now if both validateEmail and checkPassword are true, this will return true. However if either are false it will return false.
Add some logic:
function b(){return true&&false;} //false
function b(){return true||false;} //true
You need to:
onsubmit="return validateEmail()&&checkPassword();"
Have a basic registration form, trying to validate it.
I am using form serializeArray() method and loop trough the form and find if the values are null.
HTML CODE
<form name="reg" id="regform">
<fieldset>
<label for="firstname">First Name</label>
<input type="text" name="firstname" value="First Name"/>
</fieldset>
<fieldset>
<label for="lastname">Last name</label>
<input type="text" name="lastname" value="Last Name"/>
</fieldset>
<fieldset>
<label for="date">Age</label>
<input type="text" name="age"/>
</fieldset>
</form>
JQUERY Code
var formElements = $("#regform").serializeArray();
$(formElements).each(function(x)
{
if(formElements[x]["value"] == "")
{
$("[name='" + formElements[x]['name'] +"']").addClass('error');
}
});
From the above code i am able to add the class ".error" when the value is null.
Now i want the code to check the text fields values are not the default values like in my case the default values are "First Name" "Last Name"..
So i want to check even for the default values and add error class to respective element and even focus back the cursor on the first null value text field
Thanks in advance
I highly suggest using http://docs.jquery.com/Plugins/Validation. You can test for various things, such as blank values, and even extend it to detect default values.
For example:
$.validator.addMethod("name", function(value) {
return value != "First Name";
}, 'Please enter your first name.');
Alternatively you can just test against a default value with jQuery's data() function:
Working Demo: http://jsfiddle.net/WpQ2n/2/
var input = $(".name"),
defaultval = input.data("default", input.val());
// Can't submit forms in jsfid, so i just used a click event.
// Change to .submit()
$("input[type='submit']").on("click",function(e){
if(input.val()== input.data("default")){
input.addClass("error");
}
else{
// Yay it validated...
input.removeClass("error");
}
e.preventDefault();
});
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